using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;

namespace BEMSDataGateway
{
    class Creating_Setting_File
    {
        string Dir = "";
        string _strFile = "\\SettingFile";

        Form1 F1 = new Form1();
        LogFileCreate LFC = new LogFileCreate();

        public void Create_Setting_Point_File()
        {
            Dir = Environment.CurrentDirectory;

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Dir);
            System.IO.FileInfo fi = new System.IO.FileInfo(Dir + _strFile);

            if (di.Exists)
            {
                My_DB_DML MDD = new My_DB_DML();

                string ConnInfo = MDD.ConnDBInfo(); // DB접속정보를 담고 있음.

                DataSet ds = new DataSet();

                using (SqlConnection conn = new SqlConnection(ConnInfo))
                {
                    string query = "SELECT * FROM BemsMonitoringPointConfig";

                    SqlCommand cmd = new SqlCommand(query, conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandTimeout = 120;
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    cmd.Dispose();
                    try
                    {
                        conn.Open();
                        da.Fill(ds);
                        conn.Close();
                    }
                    catch (Exception e)
                    {
                        if (Form1.Enable_EnglishMode)//영어
                        {
                            LFC.Log("[Creating_Setting_File.cs] Create_Setting_Point_File Fail : " + e + " ***" + Environment.NewLine);
                        }
                        else//한글
                        {
                            LFC.Log("[Creating_Setting_File.cs] Create_Setting_Point_File 실패 : " + e + " ***" + Environment.NewLine);
                        }                    
                        conn.Close();
                    }
                    cmd.Dispose();
                    da.Dispose();
                    conn.Dispose();
                }
                try
                {
                    StreamWriter sw = new StreamWriter(new FileStream("SettingFile.csv", FileMode.Create), Encoding.UTF8);
                    WriteToStream(sw, ds.Tables[0], false, false);
                    ds.Clear();
                    ds.Dispose();
                    sw.Close();
                    sw.Dispose();
                }
                catch (Exception e)
                {              
                    if (Form1.Enable_EnglishMode)//영어
                    {
                        LFC.Log("[Creating_Setting_File.cs] WriteToStream Fail : " + e + ", ***" + Environment.NewLine);
                    }
                    else//한글
                    {
                        LFC.Log("[Creating_Setting_File.cs] WriteToStream 실패 : " + e + ", ***" + Environment.NewLine);
                    }
                }
            }
        }

        public static void WriteToStream(TextWriter stream, DataTable table, bool header, bool quoteall)
        {
            int totalcount = table.Rows.Count;

            int literal_count = 0;
            int TagCount = 0;

            foreach (DataRow row in table.Rows)
            {
                string[] Type_Store = new string[3];
                string tmpSaveMode_Store = "";
                literal_count = 0;

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    string s = row[i].ToString();
                    s = s.Trim();

                    literal_count++; // 글자수 카운트

                    if (row[i] == null)
                    {
                        return;
                    }

                    if (literal_count == 7)
                    {
                        tmpSaveMode_Store = s;
                        continue;
                    }

                    // ****************************값 Type만드는 부분
                    if (literal_count == 5 || literal_count == 6 || literal_count == 9)
                    {
                        switch (literal_count)
                        {
                            case 5: Type_Store[0] = s; break;
                            case 6: Type_Store[1] = s; break;
                            case 9: Type_Store[2] = s; break;
                        }
                        if (!(literal_count == 9))
                        {
                            continue; // 다음으로...
                        }
                        else
                        {
                            if (Type_Store[0] == "False")
                            {
                                if (Type_Store[1] == "False")
                                {
                                    if (Type_Store[2] == "False")
                                    {
                                        s = "3";
                                    }
                                    else if (Type_Store[2] == "True")
                                    {
                                        s = "6";
                                    }
                                }
                                else if (Type_Store[1] == "True")
                                {
                                    s = "1";
                                }
                            }
                            else if (Type_Store[0] == "True")
                            {
                                if (Type_Store[1] == "False")
                                {
                                    if (Type_Store[2] == "False")
                                    {
                                        s = "2";
                                    }
                                    else if (Type_Store[2] == "True")
                                    {
                                        s = "5";
                                    }
                                }
                                else if (Type_Store[1] == "True")
                                {
                                    s = "4";
                                }
                            }
                        }
                        TagCount++;
                        stream.Write(s);
                        stream.Write(',');
                        stream.Write("Tag" + TagCount);
                        stream.Write(',');
                        stream.Write(tmpSaveMode_Store);

                        stream.Flush();
                    }
                    // ****************************값 Type만드는 부분
                    else
                    {
                        stream.Write(s);
                        stream.Flush();
                    }

                    if (i >= 0 && i < 3)
                    {
                        stream.Write('.');
                    }
                    else if (i >= 3 && i < table.Columns.Count - 1)
                    {
                        stream.Write(',');
                    }
                    else
                    {
                        if (!(totalcount == TagCount)) stream.Write("\r\n");
                    }
                }
            }
            stream.Flush();
            stream.Close();
            table.Dispose();
            stream.Dispose();
        }

        public void Create_Point_File()
        {
            Dir = Environment.CurrentDirectory;

            System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(Dir);
            System.IO.FileInfo fi = new System.IO.FileInfo(Dir + _strFile);

            if (di.Exists)
            {
                My_DB_DML MDD = new My_DB_DML();

                string ConnInfo = MDD.ConnDBInfo(); // DB접속정보를 담고 있음.

                DataSet ds = new DataSet();

                using (SqlConnection conn = new SqlConnection(ConnInfo))
                {
                    string query = "SELECT * FROM BemsMonitoringPointConfig";

                    SqlCommand cmd = new SqlCommand(query, conn);
                    cmd.CommandType = CommandType.Text;
                    cmd.CommandTimeout = 120;

                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    cmd.Dispose();
                    try
                    {
                        conn.Open();
                        da.Fill(ds);
                        conn.Close();
                    }
                    catch (Exception e)
                    {
                        conn.Close();
                        if (Form1.Enable_EnglishMode)//영어
                        {
                            LFC.Log("[Creating_Setting_File.cs] Create_Point_File Fail" + e + " ,***" + Environment.NewLine);
                        }
                        else//한글
                        {
                            LFC.Log("[Creating_Setting_File.cs] Create_Point_File 실패" + e + " ,***" + Environment.NewLine);
                        }                  
                    }
                    da.Dispose();
                    conn.Dispose();
                }
                StreamWriter sw = new StreamWriter(new FileStream("TagSetFile.csv", FileMode.Create), Encoding.UTF8);
                WriteToStream_TagSetFile(sw, ds.Tables[0], false, false);
                sw.Close();
                sw.Dispose();
                ds.Dispose();
            }
        }

        public static void WriteToStream_TagSetFile(TextWriter stream, DataTable table, bool header, bool quoteall)
        {
            int totalcount = table.Rows.Count;
            int literal_count = 0;
            int TagCount = 0;

            foreach (DataRow row in table.Rows)
            {
                TagCount++;
                literal_count = 0;

                for (int i = 0; i < table.Columns.Count; i++)
                {
                    literal_count++;

                    string s = row[i].ToString();
                    s = s.Trim();

                    if (row[i] == null)
                    {
                        return;
                    }
                    if (literal_count == 8)
                    {
                        stream.Write(TagCount - 1);
                        stream.Write(',');
                        stream.Write(s);
                        stream.Flush();
                        continue;
                    }
                }
                if (!(totalcount == TagCount))
                    stream.Write("\r\n");
            }
            table.Clear();
            table.Dispose();
            stream.Flush();
            stream.Close();
            stream.Dispose();
        }
    }
}
