using System;
using System.Collections.Generic;
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}";
            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 InsertData(String sql, List<(String, object)> bindlist) {

            var ret = ExecuteNonQuery(sql, bindlist);
            if (ret == -1) {
                return Code.ResultCode.NG;
            }
            return Code.ResultCode.OK;
        }

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


    }
}
