using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.IO;
using System.Text;
using System.Diagnostics;
using System.Collections;
using System.Data.SqlClient;
using System.Timers;
using System.Threading;
using System.Runtime.InteropServices;
//Stopwatch SW = new Stopwatch();
//string sTemp1;
//SW.Reset();
//SW.Start();        
//SW.Stop();   // 현재 인스턴스가 측정한 총 경과 시간을 가져옵니다.
//sTemp1 = SW.Elapsed.ToString();
//MessageBox.Show(sTemp1);
namespace DataGateWayProject
{
    static class Program
    {
        /// 
        /// 해당 응용 프로그램의 주 진입점입니다.
        /// 
        /// 
        [STAThread]
        static void Main()
        {
            // GUID를 뮤텍스명으로 사용
            //string mtxName = "4AD31D94-659B-44A7-9277-1DD793E415D1";  
            // GUID 대신 사용자 임의대로 뮤텍스 이름 사용
            //string mtxName = "DGW";
            //Mutex mtx = new Mutex(true, mtxName);
            //// 1초 동안 뮤텍스를 획득하려 대기
            //TimeSpan tsWait = new TimeSpan(0, 0, 1);
            //bool success = mtx.WaitOne(tsWait);
            //if (!success)
            //{
            //    MessageBox.Show("프로그램이 이미 실행중입니다.");
            //    return;
            //}
            
           
            //Parsing ps = new Parsing();
            //ps.SettingFileParsing();
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new Loading_Form());  // Splash window 띄우기
            Application.Run(new Form1()); //UI 폼 열기
            
        }
    }
    //------------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------------
    //------------------------------------------------------------------------------------------------------
    /// 
    /// 타이머 스레드 클래스
    /// 
    class My_TimerThread
    {
        static string TimeCheck = "";       
        
        Parsing PS = new Parsing();
        Control_Point_Group CPG = new Control_Point_Group();
        LogFileCreate LFC = new LogFileCreate();
        System.Timers.Timer timer2 = new System.Timers.Timer();
        public static bool check = false;
        //public My_TimerThread()
        //{
        //    timer2.Elapsed += new ElapsedEventHandler(timer2_Elapsed);
        //}
        //~My_TimerThread()
        //{
        //    timer2.Elapsed -= new ElapsedEventHandler(timer2_Elapsed);
        //}
        public void timer2start()
        {
            timer2.Elapsed -= new ElapsedEventHandler(timer2_Elapsed);
            timer2.Elapsed += new ElapsedEventHandler(timer2_Elapsed);
            timer2.Interval = 2000; // 20sec 간격
           
            //timer2.Enabled = true;
            timer2.Start();
            LFC.Log("timer 시작");
        }
     
        public void timer2Stop()
        {
            timer2.Elapsed -= new ElapsedEventHandler(timer2_Elapsed);
            //System.Timers.Timer timer1 = new System.Timers.Timer();
            timer2.Stop();
            timer2.Close();
            //timer2.Enabled = false;
            //timer2.Dispose();
            LFC.Log("timer 중단");
        }
        public void timer2_Elapsed(object sender, ElapsedEventArgs e) // 1분마다 실행되는 데이터 수집 로직
        {
 
            string tmpMin = DateTime.Now.Minute.ToString(); // 현재의 '분' , if 51이라고했을때.      
            if ((TimeCheck != tmpMin) && check == false)
            {
                check = true;
                CPG.Control_Group();
                CPG.Control_Point();
                TimeCheck = PS.SettingFileParsing();
                check = false;
            }
        }        
    }
        
    /// 
    /// 결과 값을 DB에 Insert시키기 위한 클래스
    /// 
    class My_SqlDBInsert
    {
        SqlConnection conn;         //sql 접속
        LogFileCreate LFC = new LogFileCreate();
        Readini Ri = new Readini();
        Form1 SF = new Form1();
        static private bool InsertOK = false;
        /// 
        /// DB에 INSERT하기 위한 함수.
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool INsert(string FacilityTypeId, string FacilityCode, string PropertyId, object Value)
        {
            try
            {
                Ri.ReadData(); // ini의 설정값을 불러옴.
                string strcon = @"Data Source = " + Ri.UserIP + "," + Ri.UserPort + "; Initial Catalog =" + Ri.UserDB + ";Persist Security Info=True; User ID =" + Ri.UserID + "; Password =" + Ri.UserPW + "";
                conn = new SqlConnection(strcon);
                conn.Open();
                string query = "INSERT INTO BemsMonitoringPointHistory15min(SiteId,FacilityTypeId,FacilityCode,PropertyId,CreatedDateTime,CurrentValue) " +
                                "VALUES('1','" + FacilityTypeId + "','" + FacilityCode + "','" + PropertyId + "','2016-09-08 08:43:00.000','" + Value + "')"; // INSERT 쿼리문.
                SqlCommand cmd = new SqlCommand(query, conn);
                cmd.ExecuteNonQuery();
                LFC.Log(query);
                SF.DBAddressTxt.Text = "연결";
                InsertOK = true;                
            }
            catch
            {                
                SF.DBAddressTxt.Text = "연결오류";
                InsertOK = false;
            }
            finally
            {              
                conn.Dispose();
                conn.Close();             
            }
            return InsertOK;
        }
    }  
}