using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using MySql.Data.MySqlClient;


namespace CSVDownloader.Store {

    class MySqlConnectionParameter {
        public String host;
        public int port;
        public String database;
        public String user;
        public String password;
    }

    class MySQL {

        private log4net.ILog logger_ = log4net.LogManager.GetLogger("");

        protected MySqlConnection conn_;

        public MySQL(MySqlConnection conn) {
            conn_ = conn;
        }

        public static MySqlConnection GetConnection(MySqlConnectionParameter param) {
            String conn_string = $"Server={param.host}; Port={param.port}; Database={param.database}; Uid={param.user}; Pwd={param.password}; Charset='utf8'";
            var conn = new MySqlConnection(conn_string);
            conn.Open();
            return conn;
        }

        private int ExecuteNonQuery(String sql, List<(String, object)> bindlist) {

            // logger_.Debug($"{sql}");
            int ret = 0;
            using (var cmd = conn_.CreateCommand()) {
                cmd.CommandText = sql;
                foreach (var ele in bindlist) {
                    // logger_.Debug($"bind @{ele.Item1} = {ele.Item2}");
                    cmd.Parameters.AddWithValue($"@{ele.Item1}", ele.Item2);
                }

                cmd.Prepare();
                ret = cmd.ExecuteNonQuery();

            }
            return ret;
        }



        protected Code.ResultCode BulkInsertData(String tablename, DataTable table) {

            // SQL のビルド
            var sql = new StringBuilder();
            var bind_list = new List<(String, object)>();
            sql.Append($"insert into {tablename} (");

            for (int i = 0; i < table.Columns.Count; i++) {
                if (i != 0) {
                    sql.Append(",");
                }
                sql.Append($"{table.Columns[i]}");
            }
            sql.Append($") values ");


            for (int row = 0; row < table.Rows.Count; row++) {
                if (row != 0) {
                    sql.Append(",");
                }
                sql.Append("(");
                for (int col = 0; col < table.Columns.Count; col++) {
                    if (col != 0) {
                        sql.Append(",");
                    }
                    String key = $"@{table.Columns[col]}{row}";
                    sql.Append(key);


                    bind_list.Add((key, table.Rows[row][table.Columns[col]]));
                }
                sql.Append(")");
            }

            // 値のセット
            var ret = ExecuteNonQuery(sql.ToString(), bind_list);
            if (ret == -1) {
                return Code.ResultCode.NG;
            }
            return Code.ResultCode.OK;
        }

        protected int DeleteData(String sql, List<(String, object)> bindlist) {
            return ExecuteNonQuery(sql, bindlist);
        }


    }
}
