﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.DirectoryServices;
using IniParserLTK;
using System.IO;
using System.Diagnostics;
using Microsoft.Win32;
using NetworkConnection;
using System.Xml;


namespace TFS_Test_Data_Loader
{
    public partial class SelectTestTowers : Form
    {
        string filenamenew;
        public bool cancel = false;
        public Dictionary<string, int> getSystemName(string filename)
        {
            
            filenamenew = filename;
            var items = Testtowers.Items;
            List<string> result = new List<string>();

            Process netUtility = new Process();

            netUtility.StartInfo.FileName = "net.exe";

            netUtility.StartInfo.CreateNoWindow = true;

            netUtility.StartInfo.Arguments = "view";

            netUtility.StartInfo.RedirectStandardOutput = true;

            netUtility.StartInfo.UseShellExecute = false;

            netUtility.StartInfo.RedirectStandardError = true;

            netUtility.Start();

            int count_lines = 1;
            Dictionary<string, int> Testtowers_File = new Dictionary<string, int>();
            string fetch_dir = Application.StartupPath;
            if (!File.Exists(fetch_dir + "\\TestTowers.txt"))
            {
                FileStream fs = File.Create(fetch_dir + "\\TestTowers.txt");
                fs.Close();
            }
            string[] testtowers_file = File.ReadAllLines(fetch_dir + "\\TestTowers.txt");
            foreach (string s in testtowers_file)
            {
                try
                {
                    Testtowers_File.Add(s.ToUpper().ToString(), count_lines);
                }
                catch { continue; }
                count_lines++;
            }

            StreamReader streamReader = new StreamReader(netUtility.StandardOutput.BaseStream, netUtility.StandardOutput.CurrentEncoding);



            string line = "";
            Cursor.Current = Cursors.WaitCursor;

            while ((line = streamReader.ReadLine()) != null)
            {
                if (line.StartsWith("\\\\"))
                {
                    //result.Add(line.Substring(2).Substring(0, line.Substring(2).IndexOf(" ")).ToUpper());
                    try
                    {

                        Testtowers_File.Add(line.Substring(2).Substring(0, line.Substring(2).IndexOf(" ")).ToUpper(), count_lines);
                        File.AppendAllText(Application.StartupPath+"\\TestTowers.txt", line.Substring(2).Substring(0, line.Substring(2).IndexOf(" ")).ToUpper() + "\r\n");
                        count_lines++;
                    }
                    catch
                    {
                        continue;
                    }
                }

            }
            streamReader.Close();
            netUtility.WaitForExit(1000);

            return Testtowers_File;
        }
        public SelectTestTowers(string filename)
        {
            InitializeComponent();
            Dictionary<string, int> dics = getSystemName(filename);
            Testtowers.Items.Clear();
            var list = dics.Keys.ToList();
            list.Sort();
            Testtowers.Items.AddRange( list.ToArray());
           
            Cursor.Current = Cursors.Default;
        }


        

        private void Testtowers_SelectedIndexChanged(object sender, EventArgs e)
        {
          
        }

        private void button2_Click(object sender, EventArgs e)
        {
            File.WriteAllText(filenamenew, string.Empty);
            File.WriteAllText(filenamenew, Form1.Configdata);
            Form1.IsConfigure = false;
            cancel = true;
            Close();
        }
      
        private void button1_Click(object sender, EventArgs e)
        {
            this.Hide();

            FileStream oFileStream = new FileStream(filenamenew, FileMode.Create, FileAccess.ReadWrite, FileShare.None);
            oFileStream.Close();
            string t = Form1.Configdata;
            AssignTestTowers.dataforpath.Clear();

            Dictionary<string, string> Datatosave = new Dictionary<string, string>();
            if (Testtowers.CheckedItems.Cast<string>().ToList().Count > 0)
            {
                this.Dispose();
                AssignTestTowers assigntowers = new AssignTestTowers(Testtowers.CheckedItems.Cast<string>().ToList());
                assigntowers.ShowDialog();
                Datatosave = assigntowers.datatosave;
                
            }
            else
            {
                this.Show();
                return;
                
            }
            
            IniParser parser = new IniParser(filenamenew);
            int i=0;
            if (Datatosave.Count % 2 != 0)
            {
                File.WriteAllText(filenamenew, string.Empty);
                File.WriteAllText(filenamenew, Form1.Configdata);
                Form1.IsConfigure = false;
                this.Close();
                return;

            }
            foreach(KeyValuePair<string,string> kp in  Datatosave)
            {                
                if (kp.Key.ToUpper().StartsWith("TESTTOWER"))
                {
                    parser.AddSetting("ATS PATHS", kp.Key.ToUpper(), kp.Value.ToUpper());
                }
                else
                {
                    parser.AddSetting("ATS TESTTOWERS", kp.Key.ToUpper(), kp.Value.ToUpper());
                }



                #region RemoteRegistryReader

                //String ServerName = "INDELNB351";

                //// Create an object that can authenticate to a network share when you
                //// already have credentials
                //NetworkShare share = new NetworkShare(ServerName, "ipc$");

                //// Create an object that can authenticate to a network share when you
                //// do NOT already have credentials
                ////NetworkShare share = new NetworkShare(ServerName, "C$", "User", "SomePasswd");

                //// Connect to the remote drive
                //share.Connect();
                //String ProductName = string.Empty;
                //RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, ServerName);
                //if (key != null)
                //{
                //    key = key.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion");
                //    if (key != null)
                //        ProductName = key.GetValue("ProductName").ToString();
                //}
                //share.Disconnect();
                #endregion


                // hourglass cursor
                Cursor.Current = Cursors.WaitCursor;

              

                i++;
            }
            
            parser.Save();
            //Form1.IsConfigure = true;
            this.Close();
        }

        private void SelectTestTowers_Load(object sender, EventArgs e)
        {

        }
         void Form_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (File.Exists(filenamenew))
            {
                if ((File.ReadAllText(filenamenew).Length <= 5))
                {
                    File.Delete(filenamenew);
                    cancel = true;
                }
            }
            
        }

        private void Testtowers_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            //string currentItem = (string)this.Testtowers.Items[e.Index];

            //TestTowerPath.ttname = "Please paste the installation path for test tower " + currentItem.ToString();

            //TestTowerPath ttp = new TestTowerPath();

            //TTP.ttname = "Please paste the installation path for test tower " + ttname;
            //ttp.ShowDialog();
        }

        private void Testtowers_SelectedIndexChanged_1(object sender, EventArgs e)
        {

        }

        private void button3_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
            button2.Enabled = false;
            textBox1.Visible = true;
            button4.Visible = true;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            button1.Enabled = true;
            button2.Enabled = true;
            string filetext = File.ReadAllText(Application.StartupPath+"\\TestTowers.txt");
            if (filetext.Contains(textBox1.Text.ToString().Trim()))
            {
                textBox1.Visible = false;
                button4.Visible = false;
            }
            else
            {

                File.AppendAllText(Application.StartupPath+"\\TestTowers.txt", textBox1.Text.ToString() + "\r\n");
                textBox1.Visible = false;
                button4.Visible = false;
                Testtowers.Items.Clear();

                var list = getSystemName(filenamenew).Keys.ToList();
                list.Sort();
                Testtowers.Items.AddRange(list.ToArray());
                
            }
        }
    }
}
