using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using NLog;
using System.IO;                // StreamReader
using System.Data.SqlClient;    // SqlConnection
using System.Data;              // ConnectionState

namespace DBConnect
{
    public class DBConnection
    {
        Logger log = LogManager.GetLogger("target_logger");
        public Struct.ConnectStateStc ConnectDB(string home_path)
        {
            log.Debug("## Connect Database Start ##");
            bool is_connect = true;
            Struct.ConnectStateStc connect_state_struct = new Struct.ConnectStateStc();
            SqlConnection connection = new SqlConnection();
            try
            {
                string conn_path = String.Format("{0}conf\\dbconn.conn", home_path);
                FileInfo fileInfo = new FileInfo(conn_path);
                log.Debug("# database connect file exist check #");
                if (!fileInfo.Exists)
                {
                    is_connect = false;
                    Console.WriteLine("not exist connect file path");
                    log.Error("not exist connect file path");
                }
                else
                {
                    log.Debug("# load connect file #");
                    StreamReader reader = new StreamReader(conn_path);
                    string readContents = reader.ReadToEnd();
                    reader.Close();

                    string[] conn = readContents.Split('"');

                    string ip = conn[1];
                    string port = conn[3];
                    string db_name = conn[5];
                    string user = conn[7];
                    string password = conn[9];

                    // db connect
                    string dataSource = string.Format(@"{0},{1}", ip, port);
                    connection.ConnectionString = string.Format("DATA SOURCE={0};Initial Catalog={1};User id={2};Password={3};Pooling={4};Connection TImeout={5};Min Pool Size={6};Max pool Size={7}",
                        dataSource, db_name, user, password, "true", 120, 1, 10);
                    connection.Open();

                    // db connection state check
                    if (connection.State == ConnectionState.Broken || connection.State == ConnectionState.Closed)
                    {
                        is_connect = false;
                    }
                }
            } catch(Exception e)
            {
                log.Error(e.ToString);
                is_connect = false;
            }

            connect_state_struct.is_connect = is_connect;   // database connection result
            connect_state_struct.connection = connection;   // database connection info

            log.Debug("## Connect Database End ##");
            return connect_state_struct;
        }
    }
}
