using System;
using System.Collections.Generic;
using System.Data;
using Hitsuji.Framework.Utils;


namespace PostCardHitsuji.DataClient.DAO
{
    public interface IDao
    {
        void setDaoHelper(DaoEssenceAdapter essence);
    }

    public class AbsDaoHelper<T> : IDao, IDisposable where T : IDaoContentModel
    {

        #region "データアクセスエッセンス"

        private DaoEssenceAdapter daoEssence_;

        public void setDaoEssence(DaoEssenceAdapter daoEssence)
        {
            daoEssence_ = daoEssence;
        }
        public DaoEssenceAdapter getDaoEssence()
        {
            return daoEssence_;
        }

        #endregion

        #region "データコンテナ"

        public T inModel;
        public T outModel;
        public List<T> inModelList;
        public List<T> outModelList;
        protected DataSet dataSet_;

        public void setDataSet(DataSet dataSet)
        {
            dataSet_ = dataSet;
        }
        public DataSet getDataSet()
        {
            return dataSet_;
        }

        #endregion

        #region "SQLインジェクション対策"

        protected string toSafety(string val)
        {
            string result = val.Replace("'", "&quot;_");
            return result;
        }

        protected string toUnSafety(string val)
        {
            string result = val.Replace("&quot;_", "'");
            return result;
        }

        #endregion

        #region データ型を問わず、全てString型で取得する

        /// <summary>
        /// フィールドの値を String型、かつ UnSafety にフィルタして取得する
        /// </summary>
        /// <param name="field">フィールド値（ row["XXX"] ）</param>
        /// <returns></returns>
        protected string getFieldAsString(object field, string def = "")
        {
            string val = def;
            if (field.GetType().ToString().ToUpper().Equals("SYSTEM.INT32"))
                return ValueUtil.tryGetString(field, def);
            else if (field.GetType().ToString().ToUpper() == "SYSTEM.STRING")
                return toUnSafety(ValueUtil.tryGetString(field, def));
            return val;
        }

        #endregion

        public void Dispose()
        {
            daoEssence_.rollback();
            daoEssence_.closeConnection();
            daoEssence_ = null;
        }

        public void setDaoHelper(DaoEssenceAdapter essence)
        {
            this.daoEssence_ = essence;
        }
    }
}
