using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data.SQLite;

namespace CSVDownloader.Store {

    class History {
        public DateTime date;
        public String agent;
    }

    class HistoryDAO : SQLite3, IHistoryDAO {

        private static readonly String tablename_ = "History";
        private static readonly String colname_date_ = "Datetime";
        private static readonly String colname_credit_agent_ = "CreditAgent";


        private static readonly String dir_ = "data";
        private static readonly String source_ = $"{dir_}/history.db";

        public HistoryDAO() {
            if (!Directory.Exists(dir_)) {
                Directory.CreateDirectory(dir_);
            }

            Open(source_);

            String sql_create_table = "" +
                $"CREATE TABLE IF NOT EXISTS {tablename_}(" +
                $"{colname_date_}   TEXT    NOT NULL," +
                $"{colname_credit_agent_}    TEXT NOT NULL" +
                ");";

            using (var cmd = new SQLiteCommand(sql_create_table, conn_)) {
                cmd.ExecuteNonQuery();
            }

        }

        public void Save(Code.CreditAgent agent, DateTime datetime) {
            using (var cmd = conn_.CreateCommand()) {
                String replace_date = "@Datetime";
                String replace_credit_agent = "@CreditAgent";
                cmd.CommandText = $"insert into {tablename_} values ({replace_date},{replace_credit_agent});";

                String date_str = datetime.ToString();

                cmd.Parameters.Add(new SQLiteParameter(replace_date, date_str));
                cmd.Parameters.Add(new SQLiteParameter(replace_credit_agent, Code.CreditAgenciesMap.GetID(agent)));
                cmd.Prepare();

                cmd.ExecuteNonQuery();
            }
        }

        /// <summary>
        /// 直近の履歴を１つだけ取得する。
        /// </summary>
        /// <param name="agent"></param>
        /// <returns></returns>
        public List<History> GetHistory(Code.CreditAgent agent) {
            var list = new List<History>();
            using (var cmd = conn_.CreateCommand()) {
                String replace_credit_agent = "@CreditAgent";
                cmd.CommandText = $"select * from {tablename_} where {colname_credit_agent_} = {replace_credit_agent} order by  {colname_date_} desc limit 1;";

                cmd.Parameters.Add(new SQLiteParameter(replace_credit_agent, Code.CreditAgenciesMap.GetID(agent)));
                cmd.Prepare();
                using (var reader = cmd.ExecuteReader()) {
                    while (reader.Read()) {
                        var ele = new History();
                        ele.date = DateTime.Parse(reader[colname_date_].ToString());
                        ele.agent = reader[colname_credit_agent_].ToString();
                        list.Add(ele);
                    }
                }
            }
            return list;
        }


    }
}
