using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using PostCardHitsuji.DataClient.DAO;
using PostCardHitsuji.DataClient.Model;
using PostCardHitsuji.Global;
using PostCardHitsuji.Ui.RowPanel;

namespace PostCardHitsuji.Ui.Controls
{
    public partial class NewIllustLayoutUserControl : UserControl
    {

        private System.Drawing.Printing.PrintDocument printDocument = new System.Drawing.Printing.PrintDocument();
        
        public NewIllustLayoutUserControl()
        {
            InitializeComponent();
            this.Load += new EventHandler(load);
        }

        private void load(object sender, EventArgs ev)
        {
            newPaperLayer1.Visible = false;

            //イラスト
            flowLayoutPanelIllust.Controls.Clear();
            flowLayoutPanelIllust.Controls.AddRange(
                new Control[] 
                { 
                    this.createIllustRow("イラスト１", "ILLUST1"), 
                    this.createIllustRow("イラスト２", "ILLUST2"), 
                    this.createIllustRow("イラスト３", "ILLUST3"), 
                    this.createIllustRow("イラスト４", "ILLUST4"), 
                    this.createIllustRow("イラスト５", "ILLUST5"),
                    this.createIllustRow("イラスト６", "ILLUST6")
                });

            //メッセージ
            flowLayoutPanelMsg.Controls.Clear();
            flowLayoutPanelMsg.Controls.AddRange(
                new Control[] 
                { 
                    this.createMsgRow("メッセージ１", "MESSAGE1"), 
                    this.createMsgRow("メッセージ２", "MESSAGE2"), 
                    this.createMsgRow("メッセージ３", "MESSAGE3"), 
                    this.createMsgRow("メッセージ４", "MESSAGE4"), 
                    this.createMsgRow("メッセージ５", "MESSAGE5"),
                    this.createMsgRow("メッセージ６", "MESSAGE6")
                });

            checkBoxLayoutVertical.CheckedChanged += new EventHandler(checkBoxVertical_CheckedChanged);
            checkBoxLayoutVertical.Checked = true;

            newPaperLayer1.Visible = true;

        }

        private LayoutIllustItemRow createIllustRow(string title, string name)
        {
            var row = new LayoutIllustItemRow();
            row.IllustSizeItems = GlobalSettings.MultipleItems;
            row.CheckBoxTitleText = title;

            row.OnTitleCheckChangedEvent += new EventHandler(
                (sender, ev) =>
                {
                    var row_ = sender as LayoutIllustItemRow;
                    if (row_.CheckBoxTitleChecked)
                    {
                        //ON
                        row_.IllustModel.x = Math.Min(Math.Max(row_.IllustModel.x, 0), newPaperLayer1.Width - 10);
                        row_.IllustModel.y = Math.Min(Math.Max(row_.IllustModel.y, 0), newPaperLayer1.Height - 10);
                        newPaperLayer1.addIllustItem(row_.IllustModel.Name, row_.IllustModel);
                    }
                    else
                        //OFF
                        newPaperLayer1.removeIllustItem(row_.IllustModel.Name);

                });
            // イラストのプロパティ値変更後
            row.OnPropertyEditEnd += new EventHandler((sender, ev) => { newPaperLayer1.forceRefreshLayoutMethod(); });
            row.IllustModel = new IllustItemContentModel();
            row.IllustModel.Name = name;
            
            return row;
        }

        private LayoutMsgItemRow createMsgRow(string title, string name)
        {
            var row = new LayoutMsgItemRow();
            row.CheckBoxTitleText = title;
            
            //タイトルのチェックボックスクリック時の処理を登録
            row.OnTitleCheckChangedEvent += new EventHandler(
                (sender, ev) => 
                {
                    var row_ = sender as PostCardHitsuji.Ui.RowPanel.LayoutMsgItemRow;
                    if (row_.IsChecked)
                    {
                        //ON
                        row_.MsgModel.x = Math.Min(Math.Max(row_.MsgModel.x, 0), newPaperLayer1.Width - 10);
                        row_.MsgModel.y = Math.Min(Math.Max(row_.MsgModel.y, 0), newPaperLayer1.Height - 10);
                        newPaperLayer1.addMsgItem(row_.MsgModel.Name, row_.MsgModel, Color.MediumOrchid);
                    }
                    else
                        //OFF
                        newPaperLayer1.removeMsgItem(row_.MsgModel.Name);

                });
            //メッセージ変更時の処理
            row.OnPropertyEditEnd += new EventHandler( (sender, ev) => { newPaperLayer1.forceRefreshLayoutMethod(); });
            
            row.MsgModel = new MsgItemContentModel();
            row.MsgModel.Name = name;
            
            return row;
        }

        private void buttonPrint_Click(object sender, EventArgs ev)
        {
            var dialog = new PrintDialog();
            dialog.Document = printDocument;
            dialog.Document.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(pd_PrevPage);
            //プレビューするPrintDocumentを設定
            var result = dialog.ShowDialog(this);
            if (result == DialogResult.OK || result == DialogResult.Yes)
                dialog.Document.Print();
            //var printForm = new PostCardHitsuji.Frames.PrintForm(printDocument, pd_PrevPage);
            //printForm.ShowDialog(this);
        }

        private void pd_PrevPage(object sender, System.Drawing.Printing.PrintPageEventArgs ev)
        {
            getAbsoluteLayout(ev.Graphics);

            //次のページがないことを通知する
            ev.HasMorePages = false;
        }

        private void getAbsoluteLayout(System.Drawing.Graphics grp)
        {
            grp.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            grp.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;

            //画像を描画する
            SolidBrush fontBrush = null;
            //イラストを描画
            foreach (var illItem in newPaperLayer1.illustItems.Values)
            {
                var mod = illItem.model as IllustItemContentModel;
                if (mod.Enable.Equals(false.ToString().ToUpper()))
                    continue;

                if (mod.illust != null)
                    grp.DrawImage(mod.illust, mod.x, mod.y);
            }
            //メッセージを描画
            foreach (var msgItem in newPaperLayer1.msgItems.Values)
            {
                var mod = msgItem.model as MsgItemContentModel;
                if (mod.Enable.Equals(false.ToString().ToUpper()))
                    continue;

                fontBrush = new SolidBrush(mod.FontColor);
                grp.DrawString(mod.isMsgDirectVertical ?
                    mod.messageMirror : mod.message,
                    mod.font,
                    new SolidBrush(mod.FontColor),
                    mod.x,
                    mod.y,
                    mod.msgFormat);
            }
        }

        private bool checkUpdate()
        {
            if (newPaperLayer1.illustItems.Count == 0 &&
                newPaperLayer1.msgItems.Count == 0)
            {
                MessageBox.Show("イラスト・メッセージが一つも設定されていません。出力をキャンセルします。");
                return false;
            }

            return true;
        }

        private bool updateDb()
        {
            using (var daoFactory = new PostCardHitsuji.DataClient.DAO.DaoFactory())
            {
                daoFactory.beginTransaction();
                try
                {
                    //DAO生成
                    var dao = (IllustLayoutDao)daoFactory.getDao<LayoutIllustContentModel>(GlobalSettings.illLayoutDao_);
                    
                    //登録する情報DAOにパラメータとして登録
                    var layoutInfo = new IllustLayoutContentModel();
                    layoutInfo.Enable = true.ToString().ToUpper();
                    layoutInfo.layoutType = IllustLayoutContentModel.LAYOUT_TYPE_ILLUST;
                    layoutInfo.layoutVector = "V";
                    
                    foreach (var illust in newPaperLayer1.illustItems.Values)
                        layoutInfo.IllustItemList.Add(illust.model as IllustItemContentModel);
                    foreach (var msg in newPaperLayer1.msgItems.Values)
                        layoutInfo.MsgItemList.Add(msg.model as MsgItemContentModel);
                    dao.inModel = layoutInfo;
                    
                    //データ処理
                    (dao as IllustLayoutDao).updateLayoutSimple(null);

                    daoFactory.commitTransaction();
                    return true;
                }
                catch (Exception ex)
                {
                    daoFactory.rollbackTransaction();
                    System.Windows.Forms.MessageBox.Show(ex.ToString());
                    return false;
                }
            }
        }

        /// <summary>
        /// 横書き
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void checkBoxVertical_CheckedChanged(object sender, EventArgs e)
        {
            setPaperVector();
        }

        private void setPaperVector()
        {
            newPaperLayer1.Size = checkBoxLayoutVertical.Checked
                ? new Size(GlobalSettings.PaperVertical.PAPER_WIDTH, GlobalSettings.PaperVertical.PAPER_HEIGHT)
                : new Size(GlobalSettings.PaperHorizonal.PAPER_WIDTH, GlobalSettings.PaperHorizonal.PAPER_HEIGHT);
            newPaperLayer1.forceCreateGraphics();
            newPaperLayer1.forceRefreshLayoutMethod();
        }

    }

}
