using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using Advantage.Data.Provider;
using System.Data.Common;
using System.Data.OleDb;
using Microsoft.Win32;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;


namespace Advantage_Final
{


    public partial class Form1 : Form
    {
        public AdsConnection connection;
        public IDbCommand command;
        public AdsCommand paramCommand;
        public IDataReader dataReader;
        public RegistryKey Dicks = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\PanaceanTech\\ReportRunner", true);
        public RegistryKey MedisoftRoot = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\Medisoft", true);
        public RegistryKey RMRoot = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\McKesson\\RevenueManagement_1914", true);
        public List<string> list = new List<string>();
        public string line;
        public string PracticeFolder;
        public string oldPath;
       

        public Form1()

        {
            InitializeComponent();

            RegistryKey key = Microsoft.Win32.Registry.CurrentUser;
            string RootPath = ((string)MedisoftRoot.GetValue("Root Data Path"));
            key.CreateSubKey("Software\\PanaceanTech");
            RegistryKey PTech = key.OpenSubKey("Software\\PanaceanTech", true);
            PTech.CreateSubKey("ReportRunner");
            key.CreateSubKey("Software\\PanaceanTech");

            connection = new AdsConnection();
            connection.ConnectionString = "Data Source=" + RootPath +
                ";User ID=shareddatauser;Password=AndPassword" +
                ";ServerType=REMOTE|LOCAL;TrimTrailingSpaces=True";


            AdsDataReader reader;
            AdsCommand cmd;
            cmd = connection.CreateCommand();
            cmd.CommandText = "SELECT [DataSet Name], [Data Path]  FROM [MWDBLIST]";
            connection.Open();
            reader = cmd.ExecuteReader();


            while (reader.Read())
            {
                mPracticeList.Items.Add(reader.GetString(0) + " { " + reader.GetString(1));
            }

          
            connection.Close();
            


}
              
       
        




        

        private void exitToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        private void setPathsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FilePaths frmFilePaths = new FilePaths();
            frmFilePaths.ShowDialog();
            
        }



        private void InitializeDataComponents()
        {

 
        }

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new Form1());
            
        }


       private void button1_Click(object sender, EventArgs e)
       {
         for (int i = 0; i < mPracticeList.Items.Count; i++)

               mPracticeList.SetItemChecked(i, true);
       }

       private void button2_Click(object sender, EventArgs e)
       {
           
         list.Clear();

           foreach (string item in mPracticeList.CheckedItems)
           {
               string value = item;
               int i = item.IndexOf('{') + 1;
               string d = Path.Combine(value.Substring(i) + "\\ureports");
             list.Add(d);

           }

           {
              
               if ((string)Dicks.GetValue("ReportFolder") == null)
               {
                   reportFileDialog1.InitialDirectory = @"C:\";
               }
               else
               {
                   reportFileDialog1.InitialDirectory = ((string)Dicks.GetValue("ReportFolder"));
               }

               DialogResult result = reportFileDialog1.ShowDialog();
               Class1.ReportName = System.IO.Path.GetFileNameWithoutExtension(reportFileDialog1.FileName);
               if (result == DialogResult.OK)
               {
                   foreach (String file in reportFileDialog1.FileNames)
                   {
                      foreach (string item in list)
                       {
                           try
                           {
                               
                               string otherFile = Path.Combine(item, Path.GetFileName(file));
                               File.Copy(file, otherFile, true);
                           }
                           catch (UnauthorizedAccessException )
                           {
                               MessageBox.Show("Fix your fucking permissions");
                           }

                           catch (IOException)
                           {
                               MessageBox.Show("This shit doesn't exist" + item);
                           }

                           catch (Exception)
                           {

                           }
                       }



                   }

               }

           }
       }
                    

       private void button3_Click(object sender, EventArgs e)
       {

           list.Clear();

           foreach (string item in mPracticeList.CheckedItems)
           {
               string value = item;
               int i = item.IndexOf('{') + 1;
               string d = Path.Combine(value.Substring(i) + "\\mwddf.add");
               list.Add(d);
               
           }

           {

               if ((string)Dicks.GetValue("ReportFolder") == null)
               {
                   reportFileDialog1.InitialDirectory = @"C:\";
               }
               else
               {
                   reportFileDialog1.InitialDirectory = ((string)Dicks.GetValue("ReportFolder"));
               }

               DialogResult result = reportFileDialog1.ShowDialog();

               if (result == DialogResult.OK)
               {
                  
                   using (StreamReader sr = new StreamReader(reportFileDialog1.FileName))
                  {

                       line = sr.ReadToEnd();
                       
                  }

                   foreach (string item in list)
                       {
                           
                           {

                               try
                               {
                                   
                                   oldPath = item.Replace("\\mwddf.add", "");
                                   int i1 = oldPath.LastIndexOf('\\');
                                   string newPracticeName = oldPath.Substring(i1);
                                   AdsConnection conn = new AdsConnection();
                                   conn.ConnectionString = "Data Source=" + item +
                                    ";User ID=user;Password=password;" +
                                    "ServerType=REMOTE|LOCAL;TrimTrailingSpaces=True";
                                   AdsDataAdapter da = new AdsDataAdapter(line, conn);
                                   DataSet ds = new DataSet();
                                   da.SelectCommand.CommandTimeout = 0;
                                   da.Fill(ds, "Dick");
                                   DataTable dt = ds.Tables[0];
                                   string filepath = (string)Dicks.GetValue("ReportOutput", "");
                                   da.Dispose();


                                   conn.Open();
                                   AdsDataReader reader;
                                   AdsCommand PracticeName = conn.CreateCommand();
                                   PracticeName.CommandText = "SELECT [Practice Name] FROM [MWPRA]";


                                   reader = PracticeName.ExecuteReader();

                                   while (reader.Read())
                                   {

                                       PracticeFolder = reader.GetString(0);



                                   }
                                   dt.Columns.Add("Practice", typeof(string));
                                   foreach (DataRow dr in dt.Rows)
                                   {
                                       dr["Practice"] = PracticeFolder;
                                   }
                                   conn.Close();
                                   AdsConnection.FlushConnectionPool();

                                   string ReportExportPath1 = (Path.Combine((string)Dicks.GetValue("ReportOutput", "")));
                                   //string ReportExportPath1 = (Path.Combine((string)Dicks.GetValue("ReportOutput", "") + newPracticeName));
                                   string ReportExportPath = ReportExportPath1.TrimEnd('\\');
                                   bool exists = System.IO.Directory.Exists(ReportExportPath);

                                   if (!exists)
                                       System.IO.Directory.CreateDirectory(ReportExportPath);
                                
                              //     String rFilePath = (ReportExportPath + "\\" + Path.GetFileNameWithoutExtension(reportFileDialog1.FileName) + ".xlsx");
                                   String rFilePath = (ReportExportPath + "\\" + "Test" + ".xlsx");
                                   
                                   dt.ExportToExcel(rFilePath);
                                   dt.Dispose();
                                   ds.Dispose();
                                   conn.Close();

                               }
                               catch (Exception ex)
                               {
                                  

                                  string LogPath = ((Path.Combine((string)Dicks.GetValue("ReportOutput", "") + "\\" + "log.txt")));
                                  bool fileExists = File.Exists(LogPath);
                                     using (StreamWriter sw = File.AppendText(LogPath))
                                       {
                                         sw.WriteLine("");
                                         sw.WriteLine(ex);
                                         sw.WriteLine("");
                                             sw.WriteLine(oldPath);
                                                                                                                  
                                       }

                                  }
                                   continue;
                               

                   

                           }
                           
                           
                       }
             

                   }

               }
           MessageBox.Show("All Done");
           }
       
        

        private void mPracticeList_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
        {
            
        }

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

        private void openFileDialog1_FileOk_1(object sender, CancelEventArgs e)
        {

        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            foreach (int i in mPracticeList.CheckedIndices)
            {
            mPracticeList.SetItemCheckState(i,CheckState.Unchecked);
            }
        }

        private void btnScript_Click(object sender, EventArgs e)
        {

            list.Clear();

            foreach (string item in mPracticeList.CheckedItems)
            {
                string value = item;
                int i = item.IndexOf('{') + 1;
                string d = Path.Combine(value.Substring(i) + "\\mwddf.add");
                
                list.Add(d);
            }

            {

                if ((string)Dicks.GetValue("ReportFolder") == null)
                {
                    reportFileDialog1.InitialDirectory = @"C:\";
                }
                else
                {
                    reportFileDialog1.InitialDirectory = ((string)Dicks.GetValue("ReportFolder"));
                }

                DialogResult result = reportFileDialog1.ShowDialog();

                if (result == DialogResult.OK)
                {
                    using (StreamReader sr = new StreamReader(reportFileDialog1.FileName))
                    {
                        line = sr.ReadToEnd();

                    }

                    foreach (string item in list)
                    {

                        {
                            string connString = "Data Source=" + item +
                             ";User ID=user;Password=password;" +
                             "ServerType=REMOTE|LOCAL;TrimTrailingSpaces=True";
                           
                            AdsCommand justQuery = new AdsCommand();
                            justQuery.Connection = new AdsConnection(connString);
                            justQuery.CommandTimeout = 0;                          
                            justQuery.CommandText = line;
                            justQuery.Connection.Open();
                            justQuery.ExecuteNonQuery();
                            justQuery.Connection.Close();
                            AdsConnection.FlushConnectionPool();

                        }
                        
                    }

                    MessageBox.Show("I's done");
                }
                }

            }

        private void button3_Click_1(object sender, EventArgs e)
        {
            string RMPath = ((string)RMRoot.GetValue("Root Data Path"));
            mPracticeList.Items.Clear();
            connection = new AdsConnection();
            connection.ConnectionString = "Data Source=" + RMPath + "\\CMDBLIST.ADD" +
                ";User ID=user;Password=password" +
              ";ServerType=REMOTE|LOCAL;TrimTrailingSpaces=True";
            AdsDataReader reader;
            AdsCommand cmd;
            cmd = connection.CreateCommand();
            cmd.CommandText = "SELECT [Name], [CMDataPath]  FROM [Practice]";
            connection.Open();
            reader = cmd.ExecuteReader();


            while (reader.Read())
            {
                mPracticeList.Items.Add(reader.GetString(0) + " { " + reader.GetString(1));
            }


            connection.Close();

        }

        private void button4_Click(object sender, EventArgs e)
        {
            list.Clear();

            foreach (string item in mPracticeList.CheckedItems)
            {
                string value = item;
                int i = item.IndexOf('{') + 1;
                string d = Path.Combine(value.Substring(i) + "\\cm4.add");

                list.Add(d);
            }

            {

                if ((string)Dicks.GetValue("ReportFolder") == null)
                {
                    reportFileDialog1.InitialDirectory = @"C:\";
                }
                else
                {
                    reportFileDialog1.InitialDirectory = ((string)Dicks.GetValue("ReportFolder"));
                }

                DialogResult result = reportFileDialog1.ShowDialog();

                if (result == DialogResult.OK)
                {
                    using (StreamReader sr = new StreamReader(reportFileDialog1.FileName))
                    {
                        line = sr.ReadToEnd();
                    }

                    foreach (string item in list)
                    {
                        try
                        {
                            {
                                string connString = "Data Source=" + item +
                                 ";User ID=user;Password=password;" +
                                 "ServerType=REMOTE|LOCAL;TrimTrailingSpaces=True";

                                AdsCommand justQuery = new AdsCommand();
                                justQuery.Connection = new AdsConnection(connString);
                                justQuery.CommandTimeout = 0;
                                justQuery.CommandText = line;
                                justQuery.Connection.Open();
                                justQuery.ExecuteNonQuery();
                                justQuery.Connection.Close();
                                AdsConnection.FlushConnectionPool();


                            }

                        }
                        catch (Exception ex)
                            {
                                string LogPath = ((Path.Combine((string)Dicks.GetValue("ReportOutput", "") + "\\" + "log.txt")));
                                bool fileExists = File.Exists(LogPath);
                                using (StreamWriter sw = File.AppendText(LogPath))
                                {
                                    sw.WriteLine("");
                                    sw.WriteLine(ex);
                                    sw.WriteLine("");
                                    sw.WriteLine(oldPath);

                                }
                            }
                        MessageBox.Show("I's done");
                    }
                }
            }

        }

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




        }




    }

