using System;
using System.Collections.Generic;
using System.Windows.Forms;
using PostCardHitsuji.DataClient.DAO;
using PostCardHitsuji.DataClient.Model;
using PostCardHitsuji.Ui.RowPanel;
using Hitsuji.Framework.Thread;
using PostCardHitsuji.Global;
using Hitsuji.Framework.Utils;

namespace PostCardHitsuji.Ui.Controls
{
    public partial class NewMappingLayoutUserControl : UserControl
    {
        private List<IllustLayoutContentModel> layoutModels
        {
            get;
            set;
        }

        private System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();
        
        public NewMappingLayoutUserControl()
        {
            InitializeComponent();
            searchPanelMapping1.Label2 = "グループ";
            searchPanelMapping1.Label3 = "名前";
            searchPanelMapping1.Label4 = "メモ";

            Load += new EventHandler(load);
        }


        private void load(object sender, EventArgs ev)
        {
            //検索パネル
            searchPanelMapping1.SearchTextChangedEvent += new EventHandler(setRowPanelVisiblity);
            searchPanelMapping1.ButtonRefreshClickedEvent += new EventHandler(refreshRowPanelInfos);
            
            var personParam = new PersonContentModel(PersonContentModel.PersonTypes.Ignore);
            personParam.Enable = true.ToString().ToUpper();
            personParam.whoIs = "OTHER";
            var layoutParam = new IllustLayoutContentModel();
            layoutParam.Enable = true.ToString().ToUpper();
            var paramHash = new System.Collections.Hashtable();
            paramHash.Add("personParam", personParam);
            paramHash.Add("layoutParam", layoutParam);
            paramHash.Add("callback_mapping", new Action<List<PersonContentModel>, List<IllustLayoutContentModel>>(callback_Mapping));
            ThreadRunner.doProcess(paramHash, doSearch, "search__person_and_layout", true);
        }

        /// <summary>
        /// 一覧の各パネルの表示/非表示切り替え
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        private void setRowPanelVisiblity(object sender, EventArgs ev)
        {
            var textGroup = searchPanelMapping1.Text2;
            var textName = searchPanelMapping1.Text3;
            var textMemo = searchPanelMapping1.Text4;
            foreach (var ctrl in flowLayoutPanel1.Controls)
            {
                if (ctrl as MappingLayoutPanel == null) continue;

                var row = ctrl as MappingLayoutPanel;
                var model = row.Model as PersonContentModel;
                var isVisible_ConditionGroup = textGroup.Equals("") ||
                                                ValueUtil.tryGetString(model.groupName).IndexOf(textGroup) >= 0;
                var isVisible_ConditionName = textName.Equals("") ||
                                                ValueUtil.tryGetString(model.name1).IndexOf(textName) >= 0 ||
                                                ValueUtil.tryGetString(model.name2).IndexOf(textName) >= 0 ||
                                                ValueUtil.tryGetString(model.name3).IndexOf(textName) >= 0 ||
                                                ValueUtil.tryGetString(model.name4).IndexOf(textName) >= 0;
                var isVisible_ConditionMemo = textMemo.Equals("") ||
                                                 ValueUtil.tryGetString(model.memo).IndexOf(textMemo) >= 0 ||
                                                 ValueUtil.tryGetString(model.memo).IndexOf(textMemo) >= 0 ||
                                                 ValueUtil.tryGetString(model.memo).IndexOf(textMemo) >= 0;
                row.Visible = model.Id.Equals("") ||
                             (isVisible_ConditionGroup &&
                              isVisible_ConditionName &&
                              isVisible_ConditionMemo);
            }
        }

        /// <summary>
        /// UI上のパネル情報を更新していく
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        private void refreshRowPanelInfos(object sender, EventArgs ev)
        {
            var personParam = new PersonContentModel(PersonContentModel.PersonTypes.Ignore);
            personParam.Enable = true.ToString().ToUpper();
            personParam.whoIs = "OTHER";
            var layoutParam = new IllustLayoutContentModel();
            layoutParam.Enable = true.ToString().ToUpper();
            var paramHash = new System.Collections.Hashtable();
            paramHash.Add("personParam", personParam);
            paramHash.Add("layoutParam", layoutParam);
            paramHash.Add("callback_mapping", new Action<List<PersonContentModel>, List<IllustLayoutContentModel>>(callback_Mapping));
            ThreadRunner.doProcess(paramHash, doSearch, "search__person_and_layout", true);
        }

        #region search

        /// <summary>
        /// 検索
        /// </summary>
        public void doSearch(object param)
        {
            var layoutList = doSearchLayout(param);

            var personList = doSearchPerson(param);

            var callback = (param as System.Collections.Hashtable)["callback_mapping"] as Action<List<PersonContentModel>, List<IllustLayoutContentModel>>;
            if (callback != null) callback(personList, layoutList);
        }

        /// <summary>
        /// マッピング（人情報とレイアウト情報を合成）
        /// </summary>
        /// <param name="output"></param>
        private void callback_Mapping(List<PersonContentModel> personList, List<IllustLayoutContentModel> layoutList)
        {
            //空白アイテム
            var empItem = new IllustLayoutContentModel();
            empItem.Id = "-1";
            empItem.layoutName = "";
            layoutList.Insert(0, empItem);

            List<BaseRowPanel> mappingPanels = new List<BaseRowPanel>();
            MappingLayoutPanel panel = null;
            foreach (var person in personList)
            {
                panel = new MappingLayoutPanel();
                var items = new List<IllustLayoutContentModel>();
                foreach (var L in layoutList)
                {
                    var illust = new IllustLayoutContentModel();
                    illust = L;
                    items.Add(illust);
                }
                //panel.PrintDocument = printDocument;
                panel.LayoutItems = items;
                panel.Model = person;
                mappingPanels.Add(panel);
            }
            //UIにバインドするデリゲート
            Action bindAction = 
                () => 
                {
                    flowLayoutPanel1.Controls.Clear();
                    flowLayoutPanel1.Controls.AddRange(mappingPanels.ToArray()); 
                };

            if (InvokeRequired) this.Invoke(bindAction);
            else bindAction();
        }

        /// <summary>
        /// レイアウトを抽出
        /// </summary>
        /// <param name="param"></param>
        private List<IllustLayoutContentModel> doSearchLayout(object param)
        {
            var param_ = (param as System.Collections.Hashtable)["layoutParam"] as IllustLayoutContentModel;
            var callback = (param as System.Collections.Hashtable)["callback_layout"] as Action<List<IllustLayoutContentModel>>;
            using (var daoFactory = new DaoFactory())
            {
                try
                {
                    var layoutDao = (IllustLayoutDao)daoFactory.getDao<IllustLayoutContentModel>(GlobalSettings.illLayoutDao_);
                    layoutDao.inModel = param_;
                    var layoutList = layoutDao.selectSimple(null) as List<IllustLayoutContentModel>;
                    
                    return layoutList;
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }
            }
            return null;
        }
        /// <summary>
        /// レイアウトモデルを設定
        /// </summary>
        /// <param name="outputList"></param>
        private void callback_settingLayoutItems(List<IllustLayoutContentModel> outputList)
        {
            this.layoutModels = outputList;
        }

        private List<PersonContentModel> doSearchPerson(object param)
        {
            var param_ = (param as System.Collections.Hashtable)["personParam"] as PersonContentModel;
            var callback = (param as System.Collections.Hashtable)["callback_person"] as Action<List<PersonContentModel>>;
            using (var daoFactory = new DaoFactory())
            {
                try
                {
                    var personDao = (PersonDao)daoFactory.getDao<PersonContentModel>(GlobalSettings.personDao_);
                    personDao.inModel = param_;
                    var personList = personDao.selectSimple(null) as List<PersonContentModel>;
                    return personList;
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }
            }
            return null;
        }

        private void callback_settingPerson(List<PersonContentModel> outputList)
        {

        }

        #endregion //search

    }
}
