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

namespace PostCardHitsuji.Ui.RowPanel
{
    public partial class PersonFloatRowPanel : BaseFloatPanel
    {
        public PersonFloatRowPanel()
        {
            InitializeComponent();

            comboBoxGroup.ValueMember = "key";
            comboBoxWhoIs.ValueMember = "key";
            comboBoxNamePost1.ValueMember = "key";
            comboBoxNamePost2.ValueMember = "key";
            comboBoxNamePost3.ValueMember = "key";
            comboBoxNamePost4.ValueMember = "key";
            comboBoxSenderId.ValueMember = "key";
            
            comboBoxGroup.DisplayMember = "value";
            comboBoxWhoIs.DisplayMember = "value";
            comboBoxNamePost1.DisplayMember = "value";
            comboBoxNamePost2.DisplayMember = "value";
            comboBoxNamePost3.DisplayMember = "value";
            comboBoxNamePost4.DisplayMember = "value";
            comboBoxSenderId.DisplayMember = "value";

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

        private void onLoad(object sender, EventArgs ev)
        {
            //グループの選択コンボオープン時
            comboBoxGroup.DropDown += new EventHandler(comboBoxGroup_DropDown);
            buttonAddressSearch.Click += new EventHandler(
                (senderButtonAddress, evButtonAddress) =>
                {
                    var searchDialog = new PostCardHitsuji.Frames.SearchAddressFrame();
                    searchDialog.OnRowDoubleClickEvent += new DataGridViewCellEventHandler(
                        (model, evRowDoubleClick) =>
                        {
                            if (MessageBox.Show(this, "編集中の住所情報が上書きされますが宜しいですか？", "ご注意ください。", MessageBoxButtons.YesNo) == DialogResult.No) 
                                return;
                            
                            this.textBoxPre.Text = (model as AddressContentModel).postalPre;
                            this.textBoxPost.Text = (model as AddressContentModel).postalPost;
                            this.textBoxAddress1.Text = (model as AddressContentModel).address1;
                            this.textBoxAddress2.Text = (model as AddressContentModel).address2;

                        });
                    searchDialog.ShowDialog(this);
                });

            //パネル上のボタン、ラベル、その他各コントロールの見た目（色など）の設定
            this.BackColor = base.BackColor;
            attachAttribute_Button(this.button5);
            attachAttribute_Button(this.buttonAddressSearch);
            attachAttribute_Color(this.label1);
            attachAttribute_Color(this.label2);
            attachAttribute_Color(this.label6);
            attachAttribute_Color(this.labelGroup);
            attachAttribute_Color(this.labelName1);
            attachAttribute_Color(this.labelWhoIs);
            attachAttribute_Color(this.checkBoxEnable);

        }

        protected override void notifyModelChanged()
        {
            prepareUiControls();
            modelToUi();
        }

        protected override void notifyPropertyChanged(object sender, EventArgs ev)
        {

        }

        private void comboBoxGroup_DropDown(object sender, EventArgs ev)
        {
            var param = new GroupContentModel();
            param.Enable = true.ToString().ToUpper();
            doSearchGroup(param, settingComboboxGroup);
        }

        private void doSearchGroup(GroupContentModel param, Action<List<GroupContentModel>> callback)
        {
            using (var daoFactory = new DaoFactory())
            {
                try
                {
                    //データ処理
                    var dao = (GroupDao)daoFactory.getDao<GroupContentModel>(GlobalSettings.groupDao_);
                    dao.inModel = param;
                    var list = dao.selectSimple(null) as List<GroupContentModel>;

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

        private void doSearchSender(PersonContentModel param, Action<List<PersonContentModel>> callback)
        {
            using (var daoFactory = new DaoFactory())
            {
                try
                {
                    //データ処理
                    var dao = (PersonDao)daoFactory.getDao<PersonContentModel>(GlobalSettings.personDao_);
                    dao.inModel = param;
                    var list = dao.selectSimple(null) as List<PersonContentModel>;

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

        private void settingComboboxGroup(List<GroupContentModel> groupList)
        {
            var list = new List<KeyValuePair<string, string>>();
            list.Add(new KeyValuePair<string, string>("", ""));
            var selection = "";
            foreach (var item in groupList)
            {
                list.Add(new KeyValuePair<string, string>(item.Id, item.group));
                if (item.Id.Equals((Model as PersonContentModel).groupId)) selection = item.Id;
            }
            comboBoxGroup.DataSource = list;
            comboBoxGroup.SelectedValue = selection;
        }

        private void settingComboboxSender(List<PersonContentModel> senderList)
        {
            var list = new List<KeyValuePair<string, string>>();
            list.Add(new KeyValuePair<string, string>("", ""));
            var selection = "";
            foreach (var item in senderList)
            {
                list.Add(new KeyValuePair<string, string>(item.Id, item.name1 + " , " + item.name2 + "..."));
                if (item.Id.Equals((Model as PersonContentModel).Sender.Id)) selection = item.Id;
            }
            comboBoxSenderId.DataSource = list;
            comboBoxSenderId.SelectedValue = selection;
        }

        /// <summary>
        /// ＵＩ上のコンボボックスのオブジェクトにアイテム準備
        /// </summary>
        private void prepareUiControls()
        {
            var items1 = new List<KeyValuePair<string, string>>();
            var items2 = new List<KeyValuePair<string, string>>();
            var items3 = new List<KeyValuePair<string, string>>();
            var items4 = new List<KeyValuePair<string, string>>();
            foreach (var item in Global.GlobalSettings.NameSuffix)
            {
                items1.Add(new KeyValuePair<string, string>(item.Key, item.Value));
                items2.Add(new KeyValuePair<string, string>(item.Key, item.Value));
                items3.Add(new KeyValuePair<string, string>(item.Key, item.Value));
                items4.Add(new KeyValuePair<string, string>(item.Key, item.Value));
            }
            comboBoxNamePost1.DataSource = items1;
            comboBoxNamePost2.DataSource = items2;
            comboBoxNamePost3.DataSource = items3;
            comboBoxNamePost4.DataSource = items4;

            comboBoxWhoIs.DataSource = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("ME", "私"),
                new KeyValuePair<string, string>("OTHER", "外の人")
            };

            //ｸﾞﾙｰﾌﾟ
            var gParam = new GroupContentModel();
            gParam.Enable = true.ToString().ToUpper();
            doSearchGroup(gParam, settingComboboxGroup);

            //発送者
            var sParam = new PersonContentModel(PersonContentModel.PersonTypes.Ignore);
            sParam.Enable = true.ToString().ToUpper();
            sParam.whoIs = "ME";
            doSearchSender(sParam, settingComboboxSender);
        }

        /// <summary>
        /// データ移動　ＵＩからモデルへ
        /// </summary>
        /// <param name="model"></param>
        public void uiToModel(Hitsuji.Framework.DataClient.Model.IContentModel refModel)
        {
            var mod = refModel as PersonContentModel;
            if (mod == null) return;

            mod.Id = ValueUtil.tryGetString((this.Model as PersonContentModel).Id, "");
            mod.Enable = ValueUtil.tryGetString(checkBoxEnable.Checked.ToString(), "TRUE");
            if (comboBoxWhoIs.SelectedItem != null)
                mod.whoIs = comboBoxWhoIs.SelectedValue == null ? "" : ValueUtil.tryGetString(((KeyValuePair<string, string>)comboBoxWhoIs.SelectedItem).Key, "OTHER");
            mod.groupId = comboBoxGroup.SelectedItem == null ? "" : ValueUtil.tryGetString(((KeyValuePair<string, string>)comboBoxGroup.SelectedItem).Key, "");
            mod.groupName= comboBoxGroup.SelectedItem == null ? "" : ValueUtil.tryGetString(((KeyValuePair<string, string>)comboBoxGroup.SelectedItem).Value, "");
            mod.postalPre = ValueUtil.tryGetString(textBoxPre.Text, "");
            mod.postalPost = ValueUtil.tryGetString(textBoxPost.Text, "");
            mod.address1 = textBoxAddress1.Text;
            mod.address2 = textBoxAddress2.Text;
            mod.address3 = textBoxAddress3.Text;
            mod.name1 = ValueUtil.tryGetString(textBoxName1.Text, "");
            mod.name2 = ValueUtil.tryGetString(textBoxName2.Text, "");
            mod.name3 = ValueUtil.tryGetString(textBoxName3.Text, "");
            mod.name4 = ValueUtil.tryGetString(textBoxName4.Text, "");
            mod.namePost1 = comboBoxNamePost1.SelectedItem == null ? "" : ValueUtil.tryGetString(((KeyValuePair<string, string>)comboBoxNamePost1.SelectedItem).Key, "-1");
            mod.namePost2 = comboBoxNamePost2.SelectedItem == null ? "" : ValueUtil.tryGetString(((KeyValuePair<string, string>)comboBoxNamePost2.SelectedItem).Key, "-1");
            mod.namePost3 = comboBoxNamePost3.SelectedItem == null ? "" : ValueUtil.tryGetString(((KeyValuePair<string, string>)comboBoxNamePost3.SelectedItem).Key, "-1");
            mod.namePost4 = comboBoxNamePost4.SelectedItem == null ? "" : ValueUtil.tryGetString(((KeyValuePair<string, string>)comboBoxNamePost4.SelectedItem).Key, "-1");
            mod.tel = textBoxTel.Text;
            mod.memo = richTextBoxMemo.Text;
            mod.Sender.Id = comboBoxSenderId.SelectedItem == null ? "" : ValueUtil.tryGetString(((KeyValuePair<string, string>)comboBoxSenderId.SelectedItem).Key, "-1");
        }

        /// <summary>
        /// データ移動　モデルからＵＩへ
        /// </summary>
        private void modelToUi()
        {
            //モデルオブジェクトがNULLの場合、画面を初期化するため空のオブジェクトを作成する。
            //※UI上のコントロール値を全クリアするだけでもいい
            var model_ = Model == null ? new PersonContentModel(PersonContentModel.PersonTypes.Reseiver) : Model as PersonContentModel;
            this.checkBoxEnable.Checked = bool.Parse(model_.Enable);
            this.comboBoxGroup.SelectedValue
                = ValueUtil.tryGetString(model_.groupId).Equals("")
                    ? "" : ValueUtil.tryGetString(model_.groupId);
            this.comboBoxWhoIs.SelectedValue
                = ValueUtil.tryGetString(model_.whoIs).Equals("")
                    ? "OTHER" : ValueUtil.tryGetString(model_.whoIs);
            this.textBoxName1.Text = model_.name1;
            this.textBoxName2.Text = model_.name2;
            this.textBoxName3.Text = model_.name3;
            this.textBoxName4.Text = model_.name4;
            this.comboBoxNamePost1.SelectedValue
                = ValueUtil.tryGetString(model_.namePost1).Equals("") ? "" : ValueUtil.tryGetString(model_.namePost1);
            this.comboBoxNamePost2.SelectedValue
                = ValueUtil.tryGetString(model_.namePost2).Equals("") ? "" : ValueUtil.tryGetString(model_.namePost2);
            this.comboBoxNamePost3.SelectedValue
                = ValueUtil.tryGetString(model_.namePost3).Equals("") ? "" : ValueUtil.tryGetString(model_.namePost3);
            this.comboBoxNamePost4.SelectedValue
                = ValueUtil.tryGetString(model_.namePost4).Equals("") ? "" : ValueUtil.tryGetString(model_.namePost4);
            this.textBoxPre.Text = ValueUtil.tryGetString(model_.postalPre);
            this.textBoxPost.Text = ValueUtil.tryGetString(model_.postalPost);
            this.textBoxAddress1.Text = model_.address1;
            this.textBoxAddress2.Text = model_.address2;
            this.textBoxAddress3.Text = model_.address3;
            this.textBoxTel.Text = ValueUtil.tryGetString(model_.tel);
            this.richTextBoxMemo.Text = ValueUtil.tryGetString(model_.memo);
            this.comboBoxSenderId.SelectedValue
                = ValueUtil.tryGetString(model_.Sender.Id).Equals("") ? "" : ValueUtil.tryGetString(model_.Sender.Id);
        }

        protected override void margeUiToModel(Hitsuji.Framework.DataClient.Model.IContentModel refModel)
        {
            uiToModel(refModel);
        }
    }
}
