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

namespace ConnectionSrt
{
    public class Operation
    {
        public static void Generate(string ip, string port, string dbName, string username, string password, string keyName)
        {
            var connectionString = @"Data Source=" + ip.Trim() + "," + port.Trim() + ";Network Library =DBMSSOCN;" + "Initial Catalog=" + dbName.Trim() + ";User ID=" + username.Trim() + ";Password=" + password.Trim();
            RegistryKey key = Registry.CurrentUser.CreateSubKey("software\\" + keyName);
            key.SetValue("ConnectionString", connectionString);
            key.Close();
        }


        public static string CallConnection(string keyName)
        {
            string connection = string.Empty;
            RegistryKey key = Registry.CurrentUser.CreateSubKey("software\\" + keyName);
            object isValue = key.GetValue("ConnectionString");
            if (isValue == null)
            {
                return connection;
            }
            else
            {
                return key.GetValue("ConnectionString").ToString();
            }
        }
        public static string CallParameters(string keyName)
        {
            RegistryKey key = Registry.CurrentUser.CreateSubKey("software\\" + keyName);
            object isValue = key.GetValue("ConnectionString");
            if (isValue == null)
            {
                return string.Empty;
            }
            else
            {
                string parameters = string.Empty;
                string[] connection = key.GetValue("ConnectionString").ToString().Split(';');
                int count = 0;
                foreach (string con in connection)
                {
                    if (count == 0)
                    {
                        string[] ip = con.Split(',');
                        parameters += ip[0].ToString().Replace("Data Source=", "") + ",";
                        parameters += ip[1].ToString() + ",";
                    }
                    if (count == 2)
                    {
                        parameters += con.Replace("Initial Catalog=", "");
                    }
                    count++;
                }
                return parameters;
            }
        }
    }
}