using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using Renci.SshNet;

namespace WindowsFormsApp1
{
    /// <summary>
    /// DB접속을 도와주는 클래스
    /// </summary>
    class Helper_DB
    {
        // 접속
        MySqlConnection conn;

        // 쿼리
        MySqlCommand sqlcmd = new MySqlCommand();
        MySqlDataReader sd;

        public string comp_idx { get; internal set; }

        /// <summary>
        /// DB를 사용하고 싶을 때 미리 저장된 DB의 기본 접속정보를 이용하여 DB에 접근한다.
        /// </summary>
        public void DBcon()     // DB접속 함수
        {
            PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("1.215.250.130", 815, "gloriabook", "admin@!@#$");
            connectionInfo.Timeout = TimeSpan.FromSeconds(30);
            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                if (client.IsConnected)
                {
                    string strConnection = "Server=1.215.250.130;"
                                         + "Port=3306;"
                                         + "Database=unimarc;"
                                         + "uid=root;"
                                         + "pwd=Admin21234;";
                    conn = new MySqlConnection(strConnection);
                }
            }
        }
        /// <summary>
        /// 국중DB를 사용하고 싶을 때 미리 저장된 DB의 기본 접속정보를 이용하여 DB에 접근한다.
        /// </summary>
        public void DBcon_cl()     // DB접속 함수 
        {
            PasswordConnectionInfo connectionInfo = new PasswordConnectionInfo("1.215.250.130", 815, "gloriabook", "admin@!@#$");
            connectionInfo.Timeout = TimeSpan.FromSeconds(30);
            using (var client = new SshClient(connectionInfo))
            {
                client.Connect();
                if (client.IsConnected)
                {
                    string strConnection = "Server=1.215.250.130;"
                                         + "Port=3306;"
                                         + "Database=cl_marc;"
                                         + "uid=root;"
                                         + "pwd=Admin21234;";
                    conn = new MySqlConnection(strConnection);
                }
            }
        }
        /// <summary>
        /// DBcon이 선진행되어야함.
        /// SELECT * FROM [DB_Table_Name] WHERE [DB_Where_Table] LIKE \"%DB_Search_Data%\"
        /// <summary>
        /// <param name="compidx"/>이용자 회사의 idx번호 단.none일 경우 다른 DB를 가져옴</param>
        /// <param name="DB_Table_Name">테이블명</param>
        /// <param name="DB_Where_Table">검색할 테이블</param>
        /// <param name="DB_Search_Data">검색할 텍스트</param>
        /// <returns>검색된 결과값이 반환됨.</returns>
        public string DB_Contains(string DB_Table_Name, string compidx, 
                                  string DB_Where_Table = "", string DB_Search_Data = "",
                                  string Search_col = "", 
                                  string DB_Where_Table1 = "", string DB_Search_Data1 = "" )
        {
            string cmd = "SELECT ";
            if (Search_col == "") { cmd += "*"; }
            else { cmd += Search_col; }
            cmd += " FROM ";
            cmd += DB_Table_Name;
            if (DB_Table_Name == "Obj_List") { cmd += " WHERE `comp_num` = \"" + compidx + "\""; }
            else if (DB_Table_Name == "Client") { cmd += " WHERE `campanyidx` = \"" + compidx + "\""; }
            else if (DB_Table_Name == "Purchase") { cmd += " WHERE `comparyidx` = \"" + compidx + "\""; }
            else if(compidx == "none") { cmd += " WHERE `grade` = \"2\""; }
            else { cmd += " WHERE `compidx` = \"" + compidx + "\""; }
            
            if(DB_Search_Data != "")
            { 
                cmd += " AND "+ DB_Where_Table + " LIKE\"%" + DB_Search_Data + "%\"";
            }
            if(DB_Search_Data1 != "")
            { 
                cmd += " AND "+ DB_Where_Table1 + " LIKE\"%" + DB_Search_Data1 + "%\"";
            }
            cmd += ";";
            string result = "";
            // DB연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn, 즉 아까 연결한 DB
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            string change = "";
            // 한줄씩 불러오기
            while (sd.Read())
            {
                for(int cout = 0;cout < sd.FieldCount; cout++)
                {
                    change = sd[cout].ToString().Replace("|","");
                    result += change + "|";
                }
            }
            conn.Close();
            return result;
        }
        /// <summary>
        /// DBcon이 선진행되어야함. / SELECT * FROM DB_Table_Name WHERE DB_Where_Table = \"DB_Search_Data\";
        /// <summary>
        /// <param name="Search_Area">가져올 데이터의 위치</param>
        /// <param name="DB_Table_Name">테이블명</param>
        /// <param name="DB_Where_Table">검색할 테이블</param>
        /// <param name="DB_Search_Data">검색할 텍스트</param>
        /// <returns>검색된 결과값이 반환됨.</returns>
        public string DB_Select_Search(string Search_Area, string DB_Table_Name, 
            string DB_Where_Table = "", string DB_Search_Data = "",
            string DB_Where_Table1 = "", string DB_Search_Data1 = "")
        {
            string cmd = "SELECT "+Search_Area+" FROM ";
            cmd += DB_Table_Name;
            if(DB_Where_Table != "" && DB_Search_Data != "")
            {
                cmd += " WHERE `" + DB_Where_Table + "` = \"" + DB_Search_Data + "\"";
            }
            if(DB_Where_Table1 != "" && DB_Search_Data1 != "")
            {
                cmd += " AND `" + DB_Where_Table1 + "` = \"" + DB_Search_Data1 + "\"";
            }
            cmd += ";";
            string result = "";

            // DB연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn, 즉 아까 연결한 DB
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            // 한줄씩 불러오기
            while (sd.Read())
            {
                for(int cout = 0;cout< sd.FieldCount; cout++)
                {
                    result += sd[cout].ToString() + "|";
                }
            }
            conn.Close();
            return result;
        }
        /// <summary>
        /// DBcon이 선진행되어야함. / SELECT * FROM DB_Table_Name WHERE DB_Where_Table = \"DB_Search_Data\";
        /// <summary>
        /// <param name="DB_Table_Name">테이블명</param>
        /// <param name="DB_Where_Table">검색할 테이블</param>
        /// <param name="DB_Search_Data">검색할 텍스트</param>
        /// <returns>검색된 결과값이 반환됨.</returns>
        public string DB_Search(string DB_Table_Name, 
            string DB_Where_Table = "", string DB_Search_Data = "",
            string DB_Where_Table1 = "", string DB_Search_Data1 = "")
        {
            string cmd = "SELECT * FROM ";
            cmd += DB_Table_Name;// + " where id=\"id\"";
            if(DB_Search_Data != "")
            { 
                cmd += " WHERE "+ DB_Where_Table + "=\"" + DB_Search_Data +"\"";
            }
            if (DB_Where_Table1 != "" && DB_Search_Data1 != "")
            {
                cmd += " AND `" + DB_Where_Table1 + "` =\"" + DB_Search_Data1 + "\"";
            }
            cmd += ";";
            string result = "";

            // DB연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn, 즉 아까 연결한 DB
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            // 한줄씩 불러오기
            while (sd.Read())
            {
                for(int cout = 0;cout< sd.FieldCount; cout++)
                {
                    result += sd[cout].ToString() + "|";
                }
            }
            conn.Close();
            return result;
        }
        /// <summary>
        /// 여러 조건이 있을때 사용 (단, Where_Table과 Search_Date의 배열길이는 같아야함)
        /// </summary>
        /// <param name="DB_Table_Name"></param>
        /// <param name="DB_Where_Table"></param>
        /// <param name="DB_Search_Data"></param>
        /// <param name="Search_Table">추출할 열의 이름."`num1`, `num2`" 이런식으로</param>
        /// <returns></returns>
        public string More_DB_Search(String DB_Table_Name, String[] DB_Where_Table, 
            String[] DB_Search_Data, String Search_Table = "")
        {
            if(DB_Where_Table.Length != DB_Search_Data.Length) { return "오류발생"; }
            string result = "";
            string cmd = "SELECT ";
            if(Search_Table == "") { cmd += "*"; }
            else { cmd += Search_Table; }
            cmd += " FROM " + DB_Table_Name + " WHERE ";
            for(int a = 0; a < DB_Where_Table.Length; a++)
            {
                cmd += "`" + DB_Where_Table[a] + "` = \"" + DB_Search_Data[a] + "\" ";
                if(a == DB_Where_Table.Length - 1) { cmd += " LIMIT 1000;"; }
                else { cmd += " AND "; }
            }
            
            // DB연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn, 즉 아까 연결한 DB
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            // 한줄씩 불러오기
            while (sd.Read())
            {
                for(int cout = 0; cout < sd.FieldCount; cout++)
                {
                    result += sd[cout].ToString() + "|";
                }
            }
            conn.Close();
            return result;
        }
        /// <summary>
        /// DB상의 날짜의 사이값을 가져오기 위한 함수
        /// </summary>
        /// <param name="Table_name">가져올 테이블의 이름</param>
        /// <param name="Search_Table">프로그램상으로 가져올 DB데이터</param>
        /// <param name="Search_date">DB상의 날짜가 저장된 컬럼명</param>
        /// <param name="start_date">시작할 날짜 0000-00-00</param>
        /// <param name="end_date">끝낼 날짜 0000-00-00</param>
        /// <param name="compidx">회사 인덱스 main.com_idx</param>
        /// <returns></returns>
        public string Search_Date(string Table_name, string Search_Table, string Search_date, 
            string start_date, string end_date, string compidx)
        {
            string result = "";
            if (Search_Table == "") { Search_Table = "*"; }
            // select * from `table_name` where `날짜 컬럼` between date('start_date') and date('end_date')+1;
            string cmd = "SELECT " + Search_Table + " FROM `" + Table_name + "` " +
                "WHERE `comp_num` = '" + compidx + "' AND `" +
                Search_date + "` >= '" + start_date + "'";
            if(Table_name != "Obj_List") { cmd = cmd.Replace("`comp_num`", "`compidx`"); }
            if (end_date != "") { cmd += " AND `" + Search_date + "` <= '" + end_date + "';"; }
            else { cmd += ";"; }
            conn.Open();
            sqlcmd.CommandText = cmd;
            sqlcmd.Connection = conn;
            sd = sqlcmd.ExecuteReader();
            while (sd.Read()){
                for(int cout = 0; cout < sd.FieldCount; cout++)
                {
                    result += sd[cout].ToString() + "|";
                }
            }
            conn.Close();
            return result;
        }
        public void DB_INSERT(String DB_Table_name, String[] DB_col_name, String[] setData)
        {
            string cmd = "INSERT INTO " + DB_Table_name + "(";
            for(int a = 0; a < DB_col_name.Length; a++)
            {
                if (a == DB_col_name.Length - 1) { cmd += "`" + DB_col_name[a] + "`) "; }
                else { cmd += "`" + DB_col_name[a] + "`, "; }
            }
            cmd += "values(";
            for(int a = 0; a < setData.Length; a++)
            {
                if (a == setData.Length - 1) { cmd += "\"" + setData[a] + "\")"; }
                else { cmd += "\"" + setData[a] + "\", "; }
            }
            cmd += ";";
            cmd = cmd.Replace("|", "");
            using (conn)
            {
                conn.Open();
                MySqlTransaction tran = conn.BeginTransaction();
                sqlcmd.Connection = conn;
                sqlcmd.Transaction = tran;
                try
                {
                    sqlcmd.CommandText = cmd;
                    sqlcmd.ExecuteNonQuery();
                    tran.Commit();
                }
                catch(Exception ex)
                {
                    tran.Rollback();
                    MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
        /// <summary>
        /// 대상 컬럼 삭제   / DELETE FROM "DB_Table_Name" WHERE "target_idx"="comp_idx" AND "target_area"="target";
        /// </summary>
        /// <param name="DB_Table_Name">삭제할 대상이 있는 테이블명</param>
        /// <param name="target_idx">인덱스 대상이 있는 열명</param>
        /// <param name="comp_idx">삭제할 대상의 인덱스</param>
        /// <param name="target_area">삭제할 대상이 있는 열명</param>
        /// <param name="target">삭제할 대상</param>
        public void DB_Delete(string DB_Table_Name, 
            string target_idx, string comp_idx, 
            string target_area, string target)
        {
            string cmd = "DELETE FROM " + DB_Table_Name + " WHERE " +
                "`" + target_idx + "`=\"" + comp_idx + "\" AND" +
                "`" + target_area + "`=\"" + target + "\" LIMIT 1;";
            using (conn)
            {
                conn.Open();
                MySqlTransaction tran = conn.BeginTransaction();
                sqlcmd.Connection = conn;
                sqlcmd.Transaction = tran;
                try
                {
                    sqlcmd.CommandText = cmd;
                    sqlcmd.ExecuteNonQuery();

                    tran.Commit();
                }
                catch(Exception ex)
                {
                    tran.Rollback();
                    MessageBox.Show(ex.ToString());
                }
            }
        }
        /// <summary>
        /// 대상 컬럼 삭제(리미트 없음) / DELETE FROM "DB_Table_Name" WHERE "target_idx"="comp_idx" AND "target_area"="target";
        /// </summary>
        /// <param name="DB_Table">대상 테이블명</param>
        /// <param name="target_idx">회사 인덱스 컬럼명</param>
        /// <param name="comp_idx">회사 인덱스</param>
        /// <param name="target_area">삭제 대상의 컬럼명</param>
        /// <param name="target">삭제 대상</param>
        public void DB_Delete_No_Limit(string DB_Table, 
            string target_idx, string comp_idx, 
            string[] target_area, string[] target)
        {
            string cmd = string.Format("DELETE FROM {0} WHERE `{1}`= \"{2}\" AND", DB_Table, target_idx, comp_idx);
            for(int a= 0; a < target_area.Length; a++)
            {
                cmd += string.Format("`{0}`=\"{1}\"", target_area[a], target[a]);
                if (a != target_area.Length - 1) { cmd += " AND"; }
            }
            cmd += ";";
            using (conn)
            {
                conn.Open();
                MySqlTransaction tran = conn.BeginTransaction();
                sqlcmd.Connection = conn;
                sqlcmd.Transaction = tran;
                try
                {
                    sqlcmd.CommandText = cmd;
                    sqlcmd.ExecuteNonQuery();

                    tran.Commit();
                }
                catch(Exception e)
                {
                    tran.Rollback();
                    MessageBox.Show(e.ToString(), "Error");
                }
            }
        }
        /// <summary>
        /// 대상 컬럼 삭제   / DELETE FROM "DB_Table_Name" WHERE "target_idx"="comp_idx" AND "target_area"="target";
        /// </summary>
        public void DB_Delete_More_term(string DB_Table_Name, 
            string target_idx, string comp_idx, 
            string[] target_area, string[] target)
        {
            string cmd = "DELETE FROM " + DB_Table_Name + " WHERE " +
                "`" + target_idx + "`=\"" + comp_idx + "\" AND";
            for(int a = 0; a < target_area.Length; a++)
            {
                cmd += " `" + target_area[a] + "`=\"" + target[a] + "\" ";
                if (a == target_area.Length - 1) { cmd += "LIMIT 1;"; }
                else { cmd += "AND"; }
            }
            using (conn)
            {
                conn.Open();
                MySqlTransaction tran = conn.BeginTransaction();
                sqlcmd.Connection = conn;
                sqlcmd.Transaction = tran;
                try
                {
                    sqlcmd.CommandText = cmd;
                    sqlcmd.ExecuteNonQuery();

                    tran.Commit();
                }
                catch(Exception ex)
                {
                    tran.Rollback();
                    MessageBox.Show(ex.ToString(), "Error");
                }
            }
        }
        /// <summary>
        /// "UPDATE \"" + DB_Tabel_Name + "\" SET \"" + Edit_colum + "\"=\"" + Edit_Name + "\" WHERE \""+Search_Name+"\"=\"" + Search_Data + "\";"
        /// </summary>
        /// <param name="DB_Tabel_Name">테이블명</param>
        /// <param name="Edit_colum">수정할 컬럼명</param>
        /// <param name="Edit_Name">수정하고 싶은 문구</param>
        /// <param name="Search_Name">검색할 컬럼명</param>
        /// <param name="Search_Data">검색할 데이터</param>
        public string DB_Update(string DB_Tabel_Name, string Edit_colum, string Edit_Name, string Search_Name, string Search_Data)
        {
            string cmd = "UPDATE `" + DB_Tabel_Name + "` SET `" + Edit_colum + "`=\"" + Edit_Name + "\" WHERE `"+Search_Name+"`=\"" + Search_Data + "\";";
            cmd = cmd.Replace("|", "");
            using (conn)
            {
                conn.Open();
                MySqlTransaction tran = conn.BeginTransaction();
                sqlcmd.Connection = conn;
                sqlcmd.Transaction = tran;

                try
                {
                    sqlcmd.CommandText = cmd;
                    sqlcmd.ExecuteNonQuery();

                    tran.Commit();
                }
                catch(Exception ex)
                {
                    tran.Rollback();
                    MessageBox.Show(ex.ToString());
                }
            }
            return cmd;
        }
        /// <summary>
        /// 많은 곳의 데이터를 변화시키고 싶을때. 테이블명을 제외하곤 다 배열. Edit와 Search끼리의 배열 인덱스값이 각자 서로 같아야함.
        /// </summary>
        /// <param name="DB_Table_Name">바꿀 데이터가 있는 테이블명</param>
        /// <param name="Edit_col">Edit_name인덱스와 같아야함</param>
        /// <param name="Edit_name">Edit_col인덱스와 같아야함</param>
        /// <param name="Search_col">Search_Name인덱스와 같아야함</param>
        /// <param name="Search_Name">Search_col인덱스와 같아야함</param>
        public void More_Update(String DB_Table_Name, 
                        String[] Edit_col, String[] Edit_name, 
                        String[] Search_col, String[] Search_Name)
        {
            string cmd = "UPDATE `" + DB_Table_Name + "` SET ";
            for(int a = 0; a < Edit_col.Length; a++)
            {
                cmd += "`" + Edit_col[a] + "` = \"" + Edit_name[a] + "\"";
                if (a != Edit_col.Length - 1) { cmd += ", "; }
                else { cmd += " "; }
            }
            cmd += "WHERE ";
            for(int a = 0; a < Search_col.Length; a++)
            {
                cmd += "`" + Search_col[a] + "` = \"" + Search_Name[a] + "\" ";
                if (a != Search_col.Length - 1) { cmd += "AND "; }
            }
            cmd += ";";
            cmd = cmd.Replace("|", "");

            using (conn)
            {
                conn.Open();
                MySqlTransaction tran = conn.BeginTransaction();
                sqlcmd.Connection = conn;
                sqlcmd.Transaction = tran;
                try
                {
                    sqlcmd.CommandText = cmd;
                    sqlcmd.ExecuteNonQuery();
                    tran.Commit();
                }
                catch(Exception ex)
                {
                    tran.Rollback();
                    MessageBox.Show(ex.ToString());
                }
            }
        }
        /// <summary>
        /// DB에 회사이름을 검색하여 만약 있는 회사일 경우 False 반환 / 없을경우 True반환
        /// </summary>
        /// <param name="Search_Data">검색할 회사 명</param>
        /// <returns></returns>
        public bool chk_comp(string Search_Data)
        {
            string cmd = "SELECT `comp_name` FROM `Comp`;";
            // DB연결
            conn.Open();
            // 쿼리 맵핑
            sqlcmd.CommandText = cmd;
            // 쿼리 날릴 곳은 conn, 즉 아까 연결한 DB
            sqlcmd.Connection = conn;
            // 쿼리 날리기, sqlDataReader에 결과값 저장
            sd = sqlcmd.ExecuteReader();
            // 한줄씩 불러오기
            while (sd.Read())
            {
                for (int cout = 0; cout < sd.FieldCount; cout++)
                {
                    if(sd[cout].ToString() == Search_Data) { conn.Close(); return false; }
                }
            }
            conn.Close();
            return true;
        }
        /// <summary>
        /// SQL문을 직접 만들어서 작성하여 사용해야함. (단, DELETE문/UPDATE문은 사용하지말 것!)
        /// </summary>
        /// <param name="cmd">등록할 SQL문</param>
        /// <returns></returns>
        public string self_Made_Cmd(string cmd)
        {
            cmd = cmd.Replace("|", "");

            string result = "";
            if(cmd.Contains("DELETE")==true || cmd.Contains("UPDATE") == true) { return ""; }
            conn.Open();
            try
            {
                sqlcmd.CommandText = cmd;
                sqlcmd.Connection = conn;
                sd = sqlcmd.ExecuteReader();
                while (sd.Read())
                {
                    for (int cout = 0; cout < sd.FieldCount; cout++)
                    {
                        result += sd[cout].ToString() + "|";
                    }
                }
            }
            catch(Exception e)
            {
                MessageBox.Show("{0} Exception caught.\n"+ e.ToString());
                MessageBox.Show(cmd);
            }
            conn.Close();
            return result;
        }
    }
}
