using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.IO;
using System.Windows.Forms;
using System.Drawing;
using System.Threading;
using FirebirdSql.Data.FirebirdClient;

namespace IControls_FireManager
{
    // 데이타베이스는 여기 클래스에서 전담한다, 단 SQL 쿼리문은 제외함.

    public static class _Db 
    {
        ///
        /// 데이타베이스에 접속 및 쿼리 일반
        ///

        // 데이타베이스 커넥션 스트링
        public static string ConnectionString()
        {
            return string.Format("Server={0};User={1};Password={2};Database={3};Charset={4};ServerType={5}",
                                        _Data.DB_IP,        // IP ex)192.168.63.22 
                                        _Data.DB_ID,   // 사용자 
                                        _Data.DB_PassWord,  // 암호 
                                        _Data.DB_FullPath,      // 절대위치.. ex) C:\TEST\TEST.FDB 
                                        "KSC_5601",         // KSC_5601 같은 문자셋을 지정 
                                        "0");               // 0이면 Classic/Super Server, 1이면 Embedded Server를 지정하신다음... 
        }

        // 데이타베이스 접속 상태 테스트 (프로그램 시작 혹은 접속세션이 끊어질 경우 다시 접속하는 경우)
        // Fail_LOG : 실패 로그 표시 (true 인 경우에만 실패 로그를 출력한다)
        public static bool OpenTest()
        {
            FbConnection CheckFbConnection = null;
            bool ret = false;

            try
            {   
                string TestConnection = null;

                TestConnection = ConnectionString();

                // 테스트                
                if (CheckFbConnection != null) CheckFbConnection.Close();
                CheckFbConnection = new FbConnection(TestConnection);
                CheckFbConnection.Open();

                ret = (CheckFbConnection.State == ConnectionState.Open);

                if (ret == true)
                {
                    // 직전에 실패였다면 성공 LOG  
                    if (_Data.DB_Connection_Open_Ok == false)
                    {
                        // LOG   
                        _Event.DebugView_SendMessage_Write(_Text.Blank + _Text.LeftBracket + TestConnection + _Text.RightBracket + _Text.Blank + _Text.LOG_DB_Connection_Ok);

                        // 데이타베이스로 부터 정보를 읽어들임
                        //if (_Db.GET_DB_DEVICE_INFO() == true) _Event.DebugView_SendMessage_Write(_Text.LOG_DB_Device_Read_Ok);

                        //// 데이타베이스 재접속하므로 다시 UI 셋팅
                        //_Event.DbUpdate_SendMessage_Write(true);
                    }

                    // 접속성공
                    _Data.DB_Connection_Open_Ok = true;
                }
                if (CheckFbConnection != null) CheckFbConnection.Dispose();
                return ret;
            }
            catch (Exception e)
            {  
                // 직전에 성공이였다면 실패 LOG (단 처음부터 실패할 경우도 생기므로 처리함
                if (_Data.DB_Connection_Open_Ok == true || _Data.DB_Connection_FailLogOnce == false)
                {
                    _Event.DebugView_SendMessage_Write(e.ToString());
                    _Data.DB_Connection_FailLogOnce = true;
                }
                // 접속실패
                _Data.DB_Connection_Open_Ok = false;

                if (CheckFbConnection != null) CheckFbConnection.Close();
                return false;
            }
        }

        // 쓰기
        // 데이타베이스 접속후
        // SQL 쿼리 전송 
        // 세션 종료
        public static void Execute(string SQL)
        {
            // 접속 세션
            FbConnection session = null;
            // 접속된 상태의 명령어
            FbCommand command = null;
            // 접속 세션 주소
            string address = null;

            try
            {
                // 접속 세션 주소 셋팅
                address = ConnectionString();
               
                // 상위 문구를 신뢰하고 보내는 루틴
                session = new FbConnection(address);
                session.Open();
                command = new FbCommand(SQL, session);
                command.ExecuteNonQuery();

                if (session != null) session.Close();
                if (command != null) command.Dispose();
            }
            catch (Exception e)
            {
                // LOG                
                _Event.DebugView_SendMessage_Write(e.ToString() + "SQL:" + SQL);

                if (session != null) session.Close();
                if (command != null) command.Dispose();
            }
        }

        // 읽기
        // 데이타베이스 접속후
        // SQL 쿼리 전송 
        // 세션 종료
        // 쿼리 결과는 리턴 (데이타베이스 접속상태 상관없는 비연결형으로 사용하는 경우)
        public static DataRowCollection ExecuteRead_SqlDataAdapter(string SQL)
        {
            // 접속 세션
            FbConnection session = null;
            // 접속된 상태의 명령어
            FbCommand command = null;
            // 접속 세션 주소
            string address = null;
            // 접속 아답터           
            FbDataAdapter dataAdapter = null;
            DataSet dataSet = null;

            try
            {
                // 접속 세션 주소 셋팅
                address = ConnectionString();

                //// 상위 문구를 신뢰하고 보내는 루틴
                session = new FbConnection(address);
                session.Open();
                command = new FbCommand(SQL, session);

                dataAdapter = new FbDataAdapter(SQL, session);
                dataAdapter.SelectCommand = command;
                dataSet = new DataSet();
                dataAdapter.Fill(dataSet, "GetData");

                if (dataAdapter != null) dataAdapter.Dispose();
                if (session != null) session.Close();
                if (command != null) command.Dispose();
                if (dataSet != null) dataSet.Dispose();

                return dataSet.Tables["GetData"].Rows;
            }
            catch (Exception e)
            {
                // LOG                
                _Event.DebugView_SendMessage_Write(e.ToString());

                if (dataAdapter != null) dataAdapter.Dispose();
                if (session != null) session.Close();
                if (command != null) command.Dispose();
                if (dataSet != null) dataSet.Dispose();

                return null;
            }
        }
        
        
        ///
        /// 쿼리의 조합 및 특정 동작 수행
        ///

        // 특정 Table의 특정 Column에 최대값 찾기
        public static int MAX_ColumnValue(string TableName, string Column)
        {
            DataRowCollection DB_Search_ColumnMaxValue = ExecuteRead_SqlDataAdapter(_Sql.Get_ColumnMaxValue(TableName, Column));

            int MaxValue = 0;

            try
            {  
                foreach (DataRow Record in DB_Search_ColumnMaxValue)
                {
                    // 데이타가 아무것도 없다
                    if (Record[0].ToString().Length == 0)
                        return 1;

                    //DB에 저장되어 있는 레코드 수를 알자
                    MaxValue = Int32.Parse(Record[0].ToString());
                }
                return MaxValue + 1;
            }
            catch (Exception e) 
            {
                // LOG                
                _Event.DebugView_SendMessage_Write(e.ToString());

                return 1;
            }            
        }

        // DB 삽입        
        // Key_Data 의 예시 "Key1=Data1;Key2=Data2" 
        // ex) _Db.ADD("TB_TEST", "ID=1;DATA=slrclub");
        //     -> 이는 TB_TEST 테이블에 ID 컬럼에 1 값, DATA 컬럼에 slrclub 을 넣게된다 (int, string 데이타 호환은 되므로 스트링 형태로 삽입하면 됩니다)
        public static void ADD(string Table_Name, string Key_Data)
        {
            try
            {
                // SQL 생성부
                string strSQL = null;
                string tempSQL = null;
                strSQL = "insert into " + Table_Name + "(";

                // 속성 이름 임시 저장소
                string Temp_Names = _Convert.String_to_Key_Data(Key_Data, true, false); 
                // 제거 문자대로 분리시켜버림
                string[] Column_Names = Temp_Names.Split(_Convert.Result_Char);
                // 속성 값 임시 저장소
                string Temp_Values = _Convert.String_to_Key_Data(Key_Data, false, false); 
                // 제거 문자대로 분리시켜버림
                string[] Column_Values = Temp_Values.Split(_Convert.Result_Char);


                // 개수만큼 만들어서 컬럼 생성
                tempSQL = null;
                for (int i = 0; i < Column_Names.Length; i++)
                    tempSQL = tempSQL + Column_Names[i] + ",";
                // 끝문자 제거
                strSQL = strSQL + tempSQL.TrimEnd(',') + ") values (";
                // 개수만큼 만들어서 속성 값 생성
                tempSQL = null;
                for (int i = 0; i < Column_Values.Length; i++)
                    tempSQL = tempSQL + "'" + Column_Values[i] + "'" + ",";
                // 끝문자 제거
                strSQL = strSQL + tempSQL.TrimEnd(',') + ")";

                // SQL 실행부
                _Db.Execute(strSQL);


            }
            catch (Exception e)
            {
                // LOG                
                _Event.DebugView_SendMessage_Write(e.ToString());
            }
        }

        // DB 편집
        // 단, 테스트 결과 Update 를 하는 경우 INT 속성을 가지고 있는 컬럼에 String 데이터로 변경하지 못한다, 반면 반대의 경우는 허용한다.
        // Key_Data 의 예시 "Key1=Data1;Key2=Data2" 
        public static void UPDATE(string Table_Name, string Target_Key_Data, string Key_Data) 
        {
            try
            {
                // SQL 생성부
                string strSQL = null;
                string tempSQL = null;
                strSQL = "update " + Table_Name + " set ";

                // 속성 이름 임시 저장소
                string Temp_Names = _Convert.String_to_Key_Data(Key_Data, true, false); 
                // 제거 문자대로 분리시켜버림
                string[] Column_Names = Temp_Names.Split(_Convert.Result_Char);
                // 속성 값 임시 저장소
                string Temp_Values = _Convert.String_to_Key_Data(Key_Data, false, false); 
                // 제거 문자대로 분리시켜버림
                string[] Column_Values = Temp_Values.Split(_Convert.Result_Char);

                // 편집하려는 컬럼 개수만큼 , 를 추가한다
                for (int i = 0; i < Column_Names.Length; i++)
                    tempSQL = tempSQL + Column_Names[i] + "='" + Column_Values[i] + "'" + ",";
                // 끝문자 제거
                strSQL = strSQL + tempSQL.TrimEnd(',');

                // 조건절 추가
                strSQL = strSQL + " where ";//+ Target_Column_Name + "='" + Target_Column_Value + "'";

                
                // 하위코드는 다중으로 where 절을 사용할수 있도록 추가한다
                
                // 초기화                
                tempSQL = null;

                // 속성 이름 임시 저장소
                string Temp_Names_Target = _Convert.String_to_Key_Data(Target_Key_Data, true, false);
                // 제거 문자대로 분리시켜버림
                string[] Column_Names_Target = Temp_Names_Target.Split(_Convert.Result_Char);
                // 속성 값 임시 저장소
                string Temp_Values_Target = _Convert.String_to_Key_Data(Target_Key_Data, false, false);
                // 제거 문자대로 분리시켜버림
                string[] Column_Values_Target = Temp_Values_Target.Split(_Convert.Result_Char);

                // 편집하려는 컬럼 개수만큼 , 를 추가한다
                for (int i = 0; i < Column_Names_Target.Length; i++)
                    tempSQL = tempSQL + Column_Names_Target[i] + "='" + Column_Values_Target[i] + "' and ";
                // 끝문자 제거
                strSQL = strSQL + tempSQL.Remove(tempSQL.Length - 5);

                // SQL 실행부
                _Db.Execute(strSQL);

            }
            catch (Exception e)
            {
                // LOG                
                _Event.DebugView_SendMessage_Write(e.ToString());
            }
        }

        // 기존 프로젝트와 호환을 위해 특별처리 (TB_CONFIG 가 필드가 추가됨)
        //public static string TB_Config_ACCESS_EXCEPTION()
        //{
        //    string SQL = null;

        //    Execute("ALTER TABLE TB_CONFIG ADD TEST_RUN_FLAG VARCHAR(1);");
        //    Execute(" UPDATE TB_CONFIG SET TEST_RUN_FLAG='N';");
        //    Execute(" COMMIT;"); 

        //    return SQL;
        //}
    }
}