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

namespace PostCardHitsuji.Ui.Controls
{
    public partial class NewGroupUserControl : UserControl
    {
        public NewGroupUserControl()
        {
            InitializeComponent();
            searchPanel1.Label1 = "ｸﾞﾙｰﾌﾟ";
            searchPanel1.Label2 = "";
            searchPanel1.Label3 = "";
            searchPanel1.Label4 = "";

            this.Load += new EventHandler(load);
        }

        private void load(object sender, EventArgs ev)
        {
            //検索パネル
            searchPanel1.SearchTextChangedEvent += new EventHandler(setRowPanelVisiblity);
            searchPanel1.ButtonRefreshClickedEvent += new EventHandler(refreshRowPanelInfos);

            //データ検索
            var parameter = new GroupContentModel();
            parameter.Enable = "";
            var paramHash2 = new System.Collections.Hashtable();
            paramHash2.Add("param", parameter);
            paramHash2.Add("callback", new Action<object>(callback_Search));
            ThreadRunner.doProcess(paramHash2, doSearch, "group_search", true);
        }

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

                var row = ctrl as InfoRowPanel2;
                var model = row.Model as GroupContentModel;
                var isVisible_ConditionGroup = textGroup.Equals("") ||
                                               ValueUtil.tryGetString(model.group).IndexOf(textGroup) >= 0;
                row.Visible = model.Id.Equals("") || isVisible_ConditionGroup;
            }
        }

        /// <summary>
        /// UI上のパネル情報を更新していく
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        private void refreshRowPanelInfos(object sender, EventArgs ev)
        {
            //一覧更新ボタン押下時の処理
            //データ検索
            var paramRefresh = new GroupContentModel();
            paramRefresh.Enable = "";
            var paramRefreshHash = new System.Collections.Hashtable();
            paramRefreshHash.Add("param", paramRefresh);
            paramRefreshHash.Add("callback", new Action<object>(
                outputList =>
                {
                    //全てのパネルのモデルを抽出したデータで更新してく
                    foreach (var row in flowLayoutPanel1.Controls)
                    {
                        var rowPanel = row as InfoRowPanel2;
                        if (rowPanel == null) return;
                        foreach (var m in outputList as List<GroupContentModel>)
                        {
                            if ((rowPanel.Model as GroupContentModel).Id.Equals(m.Id))
                            {
                                rowPanel.Model = m;
                                break;
                            }
                        }
                    }
                }));
            ThreadRunner.doProcess(paramRefreshHash, doSearch, "group_searchForRefresh", false);
        }

        /// <summary>
        /// 検索
        /// </summary>
        public void doSearch(object paramHash)
        {
            using (var daoFactory = new DaoFactory())
            {
                var param = (paramHash as System.Collections.Hashtable)["param"] as GroupContentModel;
                var callback = (paramHash as System.Collections.Hashtable)["callback"] as Action<object>;
                try
                {
                    //DAO生成
                    var dao = (GroupDao)daoFactory.getDao<GroupContentModel>(GlobalSettings.groupDao_);
                    dao.inModel = param;

                    //データ取得
                    dao.orderDictionary.Add("id", "asc");
                    var resultDataList = dao.selectSimple(null) as List<GroupContentModel>;

                    if (resultDataList == null) return;

                    if (callback != null)
                        callback(resultDataList);
                }
                catch (Exception ex)
                {
                    //daoFactory.end(false);
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }
            }
        }

        /// <summary>
        /// 検索後の処理
        /// 一覧にパネルを表示していく
        /// </summary>
        /// <param name="modelList"></param>
        private void callback_Search(object modelList)
        {
            var modelList_ = modelList as System.Collections.IList;
            InfoRowPanel2 rowPanel = null;
            List<BaseRowPanel> detailList = new List<BaseRowPanel>();
            foreach (GroupContentModel model in modelList_)
            {
                //更新用のパネルを生成
                rowPanel = createRowPanel(model, BaseRowPanel.PanelTypes.UpdateType);
                detailList.Add(rowPanel);
            }
            //新規登録用パネル
            var mod = new GroupContentModel();
            detailList.Add(createRowPanel(mod, BaseRowPanel.PanelTypes.InsertType));

            //[bindAction アクション] 情報表示用パネルを追加していく具体的な処理内容
            Action bindAction =
                () => { flowLayoutPanel1.Controls.AddRange(detailList.ToArray()); };
            
            if (InvokeRequired) this.Invoke(bindAction);
            else bindAction();
        }

        private InfoRowPanel2 createRowPanel(GroupContentModel model, BaseRowPanel.PanelTypes type)
        {
            InfoRowPanel2 rowPanel = new InfoRowPanel2(1, 2);
            rowPanel.EditPanel = new GroupFloatRowPanel();
            rowPanel.PanelType = type;
            rowPanel.OnModelChangedEvent += new EventHandler(rowPanel_OnModelChangedEvent);
            rowPanel.SettingModelToEditPanelEvent += new EventHandler(rowPanel_SettingModelToEditPanelEvent);
            rowPanel.OnButtonUpdateClickedEvent += new EventHandler(editPanel_OnButtonUpdateClicked);
            rowPanel.Model = model;
            return rowPanel;
        }

        /// <summary>
        /// モデルオブジェクト更新時の処理
        /// パネルに表示する文字列を更新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        private void rowPanel_OnModelChangedEvent(object sender, EventArgs ev)
        {
            var row = sender as InfoRowPanel2;
            var mod = row.Model as GroupContentModel;
            if (row.Model == null) return;
            row.Title = "ID:" + mod.Id;
            var buff = new System.Text.StringBuilder();
            buff.Append("【グループ】").Append("　").AppendLine(mod.Enable.Equals("TRUE") ? "有効" : "無効")
                .Append("　").AppendLine(ValueUtil.tryGetString(mod.group));

            row.Info = buff.ToString();
        }

        private void rowPanel_OnPropertyChanged(object sender, EventArgs ev)
        {

        }

        private void rowPanel_SettingModelToEditPanelEvent(object sender, EventArgs ev)
        {
            InfoRowPanel2 rowPanel = sender as InfoRowPanel2;
            GroupFloatRowPanel editPanel = rowPanel.EditPanel as GroupFloatRowPanel;
            editPanel.Model = rowPanel.Model;
        }

        /// <summary>
        /// 更新ボタン押下処理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="ev"></param>
        private void editPanel_OnButtonUpdateClicked(object sender, EventArgs ev)
        {
            var row = sender as InfoRowPanel2;
            var param = (row.EditPanel as GroupFloatRowPanel).MargedModel.DeepCopy() as GroupContentModel;
            var checkResults = param.IsAbsoluteData();
            if (checkResults.Count > 0)
            {
                MessageBox.Show(this, checkResults[0].Content, "データ確認", MessageBoxButtons.OK);
                return;
            }
            
            if (MessageBox.Show(this,
                "データベースを更新します。よろしいですか？",
                "更新確認",
                MessageBoxButtons.OKCancel) != DialogResult.OK)
                return;

            Action<GroupContentModel> act = res =>
            {
                row.Model = res;
                MessageBox.Show("更新完了！！");
                if (row.PanelType == BaseRowPanel.PanelTypes.InsertType)
                {
                    //新規登録用だったパネルを更新用に昇格
                    row.PanelType = BaseRowPanel.PanelTypes.UpdateType;
                    //新たな新規登録用パネルを追加
                    var mod = new GroupContentModel();
                    flowLayoutPanel1.Controls.Add(createRowPanel(mod, BaseRowPanel.PanelTypes.InsertType));
                }
            };

            if (param.Id.Equals("")) insert(param, row.Model, act);
            else update(param, act);
        }

        /// <summary>
        /// DB更新
        /// </summary>
        /// <param name="model"></param>
        private void update(GroupContentModel model, Action<GroupContentModel> callback)
        {
            using (var daoFactory = new DaoFactory())
            {
                daoFactory.beginTransaction();
                try
                {
                    //DAO生成
                    var dao = (GroupDao)daoFactory.getDao<GroupContentModel>(GlobalSettings.groupDao_);
                    dao.inModel = model;
                    dao.updateSimple(null);

                    daoFactory.commitTransaction();

                    if (callback != null)
                        callback(model);
                }
                catch (Exception ex)
                {
                    daoFactory.rollbackTransaction();
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }
            }
        }

        /// <summary>
        /// DB登録
        /// </summary>
        /// <param name="model"></param>
        private void insert(GroupContentModel model,
                            BaseContentModel org, 
                            Action<GroupContentModel> callback)
        {
            using (var daoFactory = new DaoFactory())
            {
                daoFactory.beginTransaction();
                try
                {
                    //データ処理
                    var dao = (GroupDao)daoFactory.getDao<GroupContentModel>(GlobalSettings.groupDao_);
                    //新規登録時、ＩＤが振られていないため（最新+1）を設定
                    model.Id = org.Id = (dao.selectLatestId() + 1).ToString();
                    //DB登録
                    dao.inModel = model;
                    dao.insertSimple(null);

                    daoFactory.commitTransaction();

                    if (callback != null)
                        callback(model);
                }
                catch (Exception ex)
                {
                    daoFactory.rollbackTransaction();
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }
            }
        }

    }
}
