using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.OleDb;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.IO;

namespace migrate_data
{
    enum dbtype
    {
        OLEDB = 1,
        SQLDB = 2
    }
    public partial class Form1 : Form
    {
        string ACCESS_CONN = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\dspec\\RPM-97.mdb;User Id=admin;Password=;";
        string SQL_CONN = "Data Source=RPM-APP.prelub.com;Initial Catalog=access;Persist Security Info=True;User ID=mobilepmuser;Password=data4techs;";
        //string SQL_CONN = "Server=RPM-APP.prelub.com;Database=access;Username=mobilepmuser;Password=data4techs;";
        string SQL_Tables = "SELECT name FROM SYSOBJECTS WHERE xtype = 'U'";

        private DataSet data = new DataSet();
        public Form1()
        {
            InitializeComponent();
        }

        private object SqlInsert(dbtype db, string sql)
        {
            object obj = new object();
            switch (db)
            {
                case dbtype.OLEDB:
                    using (OleDbConnection conn = new OleDbConnection(ACCESS_CONN))
                    {
                        conn.Open();
                        OleDbCommand cmd = new OleDbCommand(sql);
                        cmd.Connection = conn;
                        obj = cmd.ExecuteNonQuery();
                        conn.Close();
                        conn.Dispose();
                    }
                    return obj;
                case dbtype.SQLDB:
                    using (SqlConnection sqlconn = new SqlConnection(SQL_CONN))
                    {
                        sqlconn.Open();
                        SqlCommand sqlcmd = new SqlCommand(sql);
                        sqlcmd.Connection = sqlconn;
                        sqlcmd.CommandType = CommandType.Text;
                        obj = sqlcmd.ExecuteNonQuery();
                        sqlconn.Close();
                        sqlconn.Dispose();
                    }
                    return obj;
                default:
                    return obj;
            }
        }

        private object getval(dbtype db, string sql)
        {
            object obj = new object();
            switch (db)
            {
                case dbtype.OLEDB:
                    using (OleDbConnection conn = new OleDbConnection(ACCESS_CONN))
                    {
                        conn.Open();
                        OleDbCommand cmd = new OleDbCommand(sql);
                        cmd.Connection = conn;
                        obj = cmd.ExecuteScalar();
                        conn.Close();
                        conn.Dispose();
                    }
                    return obj;
                case dbtype.SQLDB:
                    using (SqlConnection sqlconn = new SqlConnection(SQL_CONN))
                    {
                        sqlconn.Open();
                        SqlCommand sqlcmd = new SqlCommand(sql);
                        sqlcmd.Connection = sqlconn;
                        sqlcmd.CommandType = CommandType.Text;
                        obj = sqlcmd.ExecuteScalar();
                        sqlconn.Close();
                        sqlconn.Dispose();
                    }
                    return obj;
                default:
                    return obj;
            }
        }

        private DataSet getdata(dbtype db, string sql)
        {
            DataSet ds = new DataSet();
            switch (db)
            {
                case dbtype.OLEDB:
                    using (OleDbConnection conn = new OleDbConnection(ACCESS_CONN))
                    {
                        DataTable tble = new DataTable();
                        conn.Open();
                        OleDbCommand cmd = new OleDbCommand(sql);
                        cmd.Connection = conn;
                        OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
                        adapter.Fill(tble);
                        ds.Tables.Add(tble);
                        conn.Close();
                        conn.Dispose();
                    }
                    return ds;
                case dbtype.SQLDB:
                    using (SqlConnection sqlconn = new SqlConnection(SQL_CONN))
                    {
                        sqlconn.Open();
                        SqlCommand sqlcmd = new SqlCommand(sql);
                        sqlcmd.Connection = sqlconn;
                        sqlcmd.CommandType = CommandType.Text;
                        SqlDataAdapter sqladapter = new SqlDataAdapter(sqlcmd);
                        sqladapter.Fill(ds);
                        sqlconn.Close();
                        sqlconn.Dispose();
                    }
                    return ds;
                default:
                    return ds;
            }


        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //DataTable schema = null;
            //DataSet ds_sqltables = getdata(dbtype.SQLDB, SQL_Tables);
            //cb_sqltables.DataSource = ds_sqltables.Tables[0];
            //cb_sqltables.DisplayMember = ds_sqltables.Tables[0].Columns[0].ColumnName;
            //cb_sqltables.ValueMember = ds_sqltables.Tables[0].Columns[0].ColumnName;
            //using (OleDbConnection conn = new OleDbConnection(ACCESS_CONN))
            //{
            //    conn.Open();
            //    schema = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            //    //dg_data.DataSource = schema;
            //    cb_tables.DataSource = schema;
            //    cb_tables.DisplayMember = "TABLE_NAME";
            //    cb_tables.ValueMember = "TABLE_NAME";
            //    conn.Close();
            //    conn.Dispose();
            //}

        }

        //private void btn_fetch_Click(object sender, EventArgs e)
        //{
        //    using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=C:\\dspec\\db.mdb;User Id=admin;Password=;"))
        //    {
        //        DataTable schema = null;
        //        DataSet ds = new DataSet();
        //        conn.Open();
        //        OleDbCommand cmd = new OleDbCommand(string.Format("select * from {0}", cb_tables.SelectedValue.ToString()));
        //        cmd.Connection = conn;
        //        cmd.CommandType = CommandType.Text;
        //        OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);

        //        adapter.Fill(ds);
        //        dg_data.DataSource = ds.Tables[0];
        //        cb_tables.DataSource = schema;
        //        cb_tables.DisplayMember = "TABLE_NAME";
        //        cb_tables.ValueMember = "TABLE_NAME";
        //    }
        //}

        public class MyObj
        {
            public MyObj() { }
            public MyObj(string strdate, int MyInt, string strError)
            {
                date = strdate;
                myid = MyInt;
                error = strError;
            }
            public string date { get; set; }
            public int myid { get; set; }
            public string error { get; set; }
        }

        private void btn_FetchParts_Click(object sender, EventArgs e)
        {

            string sql = "Update z_parts set createDate = '{0}' where myid = {1}";
            DataSet ds = getdata(dbtype.SQLDB, "Select [Date], myid from z_parts where [Date] is not null");
            List<MyObj> list = new List<MyObj>();
            foreach (DataRow row in ds.Tables[0].Rows)
            {
                string val = row.ItemArray[0].ToString();
                try
                {
                    DateTime dt = DateTime.Parse(row.ItemArray[0].ToString());
                    using (SqlConnection conn = new SqlConnection(SQL_CONN))
                    {
                        conn.Open();
                        SqlCommand sqlcmd = new SqlCommand(string.Format(sql, dt, Convert.ToInt32(row.ItemArray[1])));
                        sqlcmd.Connection = conn;
                        sqlcmd.CommandType = CommandType.Text;
                        sqlcmd.ExecuteNonQuery();
                        conn.Close();
                        conn.Dispose();
                    }
                }
                catch (Exception ex)
                {
                    list.Add(new MyObj(val, Convert.ToInt32(row.ItemArray[1]), ex.Message));
                }

            }
            Console.Write(list.ToString());
        }

        private struct dspec
        {
            public int id { get; set; }
            public string number { get; set; }
            public string rev { get; set; }
            public string error { get; set; }
            public string qry { get; set; }
            
        }
        private void button1_Click(object sender, EventArgs e)
        {
            
            int counter = 1;
            string sql = "select ID, [RPM Part Number], [General Design Specs].ERN as ERN from [General Design Specs] where [RPM Part Number] > 0 and ERN > -1 and ID in (10253,21872,31531,32342,36717,36277,36642,38719,39439,39822);";
            List<DataRow> rows = new List<DataRow>();
            List<dspec> dspecs = new List<dspec>();
            DataSet ids = getdata(dbtype.OLEDB, sql);
            foreach (DataRow row in ids.Tables[0].Rows)
            {
                GDSpecObj obj = new GDSpecObj();
                try
                {
                    DataSet ds = getdata(dbtype.OLEDB, string.Format("select * from [General Design Specs] where ID = {0};", row.ItemArray[0]));
                    foreach (DataRow r in ds.Tables[0].Rows)
                    {
                        rows.Add(r);

                        obj.SetVals(r);
                        string query = obj.ReturnQuery();
                        object retObj = SqlInsert(dbtype.SQLDB, query);
                        Console.WriteLine(query);

                    }
                    Console.WriteLine(string.Format("{0} Success", counter));
                }
                catch (Exception ex)
                {
                    dspecs.Add(new dspec() { id = Convert.ToInt32(row.ItemArray[0]), number = row.ItemArray[1].ToString(), rev = row.ItemArray[2].ToString(), error = ex.Message, qry = obj.ReturnQuery() });
                    Console.WriteLine(string.Format("{0} Fail", counter));
                }
                counter += 1;
            }
            StringBuilder sb = new StringBuilder();
            foreach (dspec d in dspecs)
            {
                sb.AppendLine(string.Format("\"{0}\", \"{1}\", \"{2}\", \"{3}\"", d.id.ToString(), d.number.ToString(), d.rev.ToString(), d.error));
            }
            using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"c:\dspec\errors.csv"))
            {
                file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
            }
            Console.Write(dspecs.ToString());
        }

        private void btn_mspec_Click(object sender, EventArgs e)
        {
            string query = string.Empty;
            StringBuilder success = new StringBuilder();
            StringBuilder fail = new StringBuilder();
            int counter = 1;
            string sql = "select ID, [RPM Part Number], [Motor Specs].ERN as ERN from [Motor Specs] WHERE [RPM Part Number] > -1 and [Motor Specs].ERN > -1 and [Motor Specs].ID in (1712,1666,1675,1679,1688,1690,1692,1697,1698) ;";
            List<DataRow> rows = new List<DataRow>();
            List<dspec> dspecs = new List<dspec>();
            DataSet ids = getdata(dbtype.OLEDB, sql);
            foreach (DataRow row in ids.Tables[0].Rows)
            {
                MDspecObj obj = new MDspecObj();
                try
                {
                    DataSet ds = getdata(dbtype.OLEDB, string.Format("select * from [Motor Specs] where ID = {0};", row.ItemArray[0]));
                    foreach (DataRow r in ds.Tables[0].Rows)
                    {
                        obj.SetVals(r);
                        query = obj.Qry();
                        object retObj = SqlInsert(dbtype.SQLDB, query);
                        string successMsg = string.Format("Try #: {0} Success for Part#: {1}, ID={2}", counter, row.ItemArray[1], row.ItemArray[0]);
                        success.AppendLine(successMsg);
                        txt_Success.Text = success.ToString();
                        Console.WriteLine(successMsg);
                        counter += 1;

                    }
                }
                catch (Exception ex)
                {
                    string failMsg = string.Format("Try #: {0} Failed for Part#: {1}, ID={2}, ERROR: {3}", counter, row.ItemArray[1], row.ItemArray[0], ex.Message);
                    
                    fail.AppendLine(failMsg);
                    txt_fail.Text = fail.ToString();
                    Console.WriteLine(failMsg);
                    counter += 1;
                }
            }
        }
        struct fieldinfo
        {
            public string name { get; set; }
            public Type type { get; set; }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            StringBuilder errors = new StringBuilder();
            DateTime start, finish;
            start = DateTime.Now;
            int counter = 1;
            string msg = "Try: {0}, Status: {1}, index{2}";
            Bom bom = new Bom();
            string sql = "select * from BOM where ID is not null;";
            DataSet ds = getdata(dbtype.OLEDB, sql);
            Console.WriteLine(start);
            for(int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                try
                {
                    sql = bom.InsertStatement(ds.Tables[0].Rows[i]);
                    SqlInsert(dbtype.SQLDB, sql);
                    Console.WriteLine(string.Format(msg, counter, "success", i));
                }
                catch (Exception ex)
                {
                    Console.WriteLine(string.Format(msg, counter, "fail: " + ex.Message, i));
                    errors.AppendLine(string.Format(msg, counter, "fail: " + ex.Message, i) + "   " + sql);
                }
            }
            finish = DateTime.Now;
            Console.WriteLine(errors.ToString());
            Console.WriteLine("Started: " + start + "        finished: " + finish);

        }

        private void button3_Click(object sender, EventArgs e)
        {
            string sql = "select 'Insert Into \"Bom\"(\"old\", \"new\", \"partNumberId\", \"viewLocationId\", \"designSpecId\", \"createDate\", \"createUserId\", \"updateDate\", \"updateUserId\")'	+ 'values('	"
    + "+ case when b.[old] IS null then 'null' else '''' + b.[old] + '''' end + ', '	"
    + "+ case when b.[new] IS null then 'null' else '''' + b.[new] + '''' end + ', '	"
    + "+ case when b.[partId] IS null then 'null' else cast(b.[partId] as varchar(50)) end	+ ', '	"
    + "+ case when b.[viewLocationId] IS null then 'null' else cast(b.[viewLocationId] as varchar(50)) end	+ ', '"
    + "+ case when b.[dspecId] IS null then 'null' else cast(b.[dspecId] as varchar(50)) end "
    + "+ ', now(), -1, now(), -1);' "
+ " from z_bom b"
    + " inner join tempdspec gd on gd.id = b.dspecId";
            string basePath = "\\\\192.168.0.220\\mcarman\\dspec\\boms\\insertboms{0}.sql";
            int batch = 1;
            string myfile = string.Format(basePath, batch);
            DataSet sqlDs = getdata(dbtype.SQLDB, sql);
            int counter = 1;
            Console.WriteLine(string.Format("Batch: {0}", batch));
            foreach (DataRow row in sqlDs.Tables[0].Rows)
            {
                if (counter > 25000)
                {
                    counter = 1;
                    batch = batch + 1;
                    myfile = string.Format(basePath, batch);
                    Console.WriteLine(string.Format("Batch: {0}", batch));
                }
                using (StreamWriter sw = File.AppendText(myfile))
                {
                    sw.WriteLine(row.ItemArray[0].ToString());
                    Console.Write(string.Format("Counter: {0};", counter));
                }
                counter += 1;
                    
            }
        }

        /*
                                                                                                                                                                     Index: 0, Name: RPM Part Number
                                                                                                                                                            Index: 1, Name: Customer					cust
                                                                                                                                                            Index: 2, Name: Customer Part Number				custpn
                                                                                                                                                            Index: 3, Name: Primary Vendor					pvend
                                                                                                                                                            Index: 4, Name: Primary Vendor Part #				pvendpn
                                                                                                                                                            Index: 5, Name: Secondary Vendor				secvend
                                                                                                                                                            Index: 6, Name: Secondary Vendor Part #				secvendpn
                                                                                                                                                            Index: 7, Name: RPM PART UNFIN					rpmptunfin
                                                                                                                                                            Index: 8, Name: DELCO PART UNFIN				delcoptunfin
                                                                                                                                                            Index: 9, Name: DELCO PART FIN					delcoptfin
                                                                                                                                                            Index: 10, Name: CAT PART					catpt
                                                                                                                                                            Index: 11, Name: CUM PART					cumpt
                                                                                                                                                            Index: 12, Name: D R PART					drpt
                                                                                                                                                            Index: 13, Name: DDC PART					ddcpt
                                                                                                                                                            Index: 14, Name: PARKER PART					parkerpt
                                                                                                                                                            Index: 15, Name: Parker Part Description			parkerptdescription
                                                                                                                                                            Index: 16, Name: Komatsu Part					komatsupt
                                                                                                                                                            Index: 17, Name: OTHER PART					otherpt
         */

        private void button4_Click(object sender, EventArgs e)
        {
            List<string> list = new List<string>();
            string accesssql = "SELECT [Part Numbers].[RPM Part Number], [Part Numbers].Customer, [Part Numbers].[Customer Part Number], [Part Numbers].[Primary Vendor], [Part Numbers].[Primary Vendor Part #], [Part Numbers].[Secondary Vendor], [Part Numbers].[Secondary Vendor Part #], [Part Numbers].[RPM PART UNFIN], [Part Numbers].[DELCO PART UNFIN], [Part Numbers].[DELCO PART FIN], [Part Numbers].[CAT PART], [Part Numbers].[CUM PART], [Part Numbers].[D R PART], [Part Numbers].[DDC PART], [Part Numbers].[PARKER PART], [Part Numbers].[Parker Part Description], [Part Numbers].[Komatsu Part], [Part Numbers].[OTHER PART] FROM [Part Numbers];";
            DataTable accesstable = getdata(dbtype.OLEDB, accesssql).Tables[0];
            string pgsql = "Update \"PartNumber\" set \"cust\" = {0}, \"custpn\" = {1}, \"pvend\" = {2}, \"pvendpn\" = {3}, \"secvend\" = {4}, \"secvendpn\" = {5}, \"rpmptunfin\" = {6}, \"delcoptunfin\" = {7}, \"delcoptfin\" = {8}, \"catpt\" = {9}, \"cumpt\" = {10}, \"drpt\" = {11}, \"ddcpt\" = {12}, \"parkerpt\" = {13}, \"pakerptdescription\" = {14}, \"komatsupt\" = {15}, \"otherpt\" = {16} where \"partNumber1\" = '{17}';";
            for (int i = 0; i < accesstable.Rows.Count; i++)
            {
                DataRow row = accesstable.Rows[i];
                string sql = string.Format(pgsql
                    , row.ItemArray[1].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[1].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[2].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[2].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[3].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[3].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[4].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[4].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[5].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[5].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[6].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[6].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[7].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[7].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[8].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[8].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[9].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[9].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[10].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[10].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[11].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[11].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[12].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[12].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[13].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[13].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[14].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[14].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[15].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[15].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[16].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[16].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[17].ToString().Trim().Length == 0 ? "null" : "'" + row.ItemArray[17].ToString().Trim().Replace("'", "") + "'"
                    , row.ItemArray[0].ToString().Trim().Length == 0 ? "null" : row.ItemArray[0].ToString().Trim());
                list.Add(sql);
            }
            string pathtonewfile = @"\\NAS35939B.prelub.com\mcarman\Access_to_Postgres_sql_files\UpdatePartNumbers.sql";
            string newsqlfile = string.Join("\r\n", list);
            using (StreamWriter output = new StreamWriter(pathtonewfile))
            {
                foreach (string line in list)
                    output.WriteLine(line);
            }

            //Insert Statement read into string list
            string sqlFile = @"\\NAS35939B.prelub.com\mcarman\Access_to_Postgres_sql_files\XCustomerParts.sql";
            string sqlTxt = File.ReadAllText(sqlFile);
            Console.WriteLine(sqlTxt);
            list.Add(sqlTxt);
           

            PGHelper helper = new PGHelper();
            helper.MakeSSHTunnel("pn", list);


        }
    }
}
