﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security;
using System.Text;
using System.Threading.Tasks;

namespace EnvironmentEditor.Reg
{
    class RegHelper
    {
        /// <summary>
        /// open a registry by a key
        /// </summary>
        /// <param name="baseRegistryKey">the base registry key</param>
        /// <param name="keyPath">the key path to be opened</param>
        /// <param name="seperator">the key seperator</param>
        /// <returns></returns>
        public static RegistryKey openExistingKeyWritable(RegistryKey baseRegistryKey, string keyPath, string seperator = "/")
        {
            return openExistingKeyWritable(baseRegistryKey, keyPath, seperator, true);
        }

        private static RegistryKey openExistingKeyWritable(RegistryKey baseRegistryKey, string keyPath, string seperator, bool writable)
        {
            string[] keys = keyPath.Split(seperator.ToCharArray());
            RegistryKey parentReg = baseRegistryKey;
            foreach (string key in keys)
            {
                try
                {
                    parentReg = parentReg.OpenSubKey(key, writable);
                }
                catch (ArgumentNullException ae)
                {
                    throw new RegException("Invalid parameter.", ae);
                }
                catch (ObjectDisposedException ode)
                {
                    throw new RegException(ode.Message, ode);
                }
                catch (SecurityException see)
                {
                    throw new RegException(see.Message, see);
                }
            }
            return parentReg;
        }

        public static void set(RegistryKey registryKey, string key, string value)
        {
            registryKey.SetValue(key, value);
        }
        public static void delete(RegistryKey registryKey, string key)
        {
            registryKey.DeleteValue(key);
        }
        public static Dictionary<string, string> listAllKeys(RegistryKey registryKey)
        {
            try
            {
                Dictionary<string, string> regKeyValues = new Dictionary<string, string>();
                string[] keys = registryKey.GetValueNames();
                
                foreach (string key in keys)
                {
                    object value = registryKey.GetValue(key);
                    regKeyValues.Add(key, value == null? null : value.ToString());
                }

                return regKeyValues;
            }
            catch(Exception e)
            {
                throw new RegException(e);
            }
           
        }
    }
}
