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

namespace PostCardHitsuji.Frames
{
    public partial class SearchAddressFrame : Form
    {
        public event DataGridViewCellEventHandler OnRowDoubleClickEvent;


        public SearchAddressFrame()
        {
            InitializeComponent();
            this.dataGridView1.AutoGenerateColumns = false;
            this.ColumnPostalPre.DataPropertyName = "postalPre";
            this.ColumnPostalPost.DataPropertyName = "postalPost";
            this.ColumnAddress1.DataPropertyName = "address1";
            this.ColumnAddress2.DataPropertyName = "address2";

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

        private void load(object sender, EventArgs ev)
        {
            dataGridView1.CellDoubleClick += new DataGridViewCellEventHandler(onCellDoubleClickMethod);

            search();
        }

        private void search()
        {
            using (var daoFactory = new DaoFactory())
            {
                try
                {
                    //DAO生成
                    var dao = daoFactory.getDao<AddressContentModel>(GlobalSettings.addressDao_) as AddressDao;
                    //SQLでパラメータに利用するデータモデルクラスを用意
                    var paramContentModel = new AddressContentModel();
                    paramContentModel.Enable = true.ToString().ToUpper();
                    dao.inModel = paramContentModel;

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

                    //データディスプレーに表示
                    dataGridView1.DataSource = resultDataList;
                }
                catch (Exception ex)
                {
                    //daoFactory.end(false);
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                }
            }
        }

        private void onCellDoubleClickMethod(object sender, DataGridViewCellEventArgs ev)
        {
            if (ev.RowIndex == -1 || ev.ColumnIndex == -1) return;

            var model = dataGridView1.Rows[ev.RowIndex].DataBoundItem;
            if (OnRowDoubleClickEvent != null)
                OnRowDoubleClickEvent(model, ev);

            this.Close();
        }
    }
}
