// 下水データ管理システム
// Copyright (C) 2018 公益財団法人とちぎ建設技術センター(https://www.tochigictc.or.jp/)
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.If not, see<http://www.gnu.org/licenses/>.

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;

namespace WindowsFormsApplication1 {
    public partial class Form30PrintPreviewBase : Form {
        public Form30PrintPreviewBase() {
            InitializeComponent();
            printPreviewControl1.Cursor = Cursors.Default;
        }

        int totalPageCount;
        int tempPageCount;
        int viewPage = 1;
        int copiesParPage = 1;
        int copyTimes;
        bool paperPrinting = false;

        int[] zoomLevelSet = { 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 150, 170, 200, 250, 300, 400, 500 };
        decimal zoomLevel;




        //ロード時イベント
        private void printPreview_Shown(object sender, EventArgs e) {
            makePrintPageIvent();
            setPrintArea();
            previewZoom(true);
            button8.Enabled = false;
        }




        //PrintDocumentオブジェクトの作成
        protected PrintDocument printDocument1 = new PrintDocument();

        private void makePrintPageIvent() {
            printDocument1.PrintPage += new PrintPageEventHandler(printDocumentPrintPage);
            printDocument1.DefaultPageSettings.Margins.Left = PrintArea.marginL;
            printDocument1.DefaultPageSettings.Margins.Right = PrintArea.marginR;
            printDocument1.DefaultPageSettings.Margins.Top = PrintArea.marginT;
            printDocument1.DefaultPageSettings.Margins.Bottom = PrintArea.marginB;
            printDocument1.OriginAtMargins = false;
        }




        //ページ設定ボタンクリックイベント
        private void button2_Click(object sender, EventArgs e) {
            PageSetupDialog pageSetupDialog1 = new PageSetupDialog();
            pageSetupDialog1.EnableMetric = true;
            pageSetupDialog1.Document = printDocument1;
            pageSetupDialog1.PageSettings.Margins = printDocument1.DefaultPageSettings.Margins;

            if(pageSetupDialog1.ShowDialog() == DialogResult.OK) {
                setPrintArea();
                makePreview();
            }
        }




        //印刷ボタンクリックイベント
        private void button3_Click(object sender, EventArgs e) {
            PrintDialog printDialog1 = new PrintDialog();
            printDialog1.Document = printDocument1;
            printDialog1.UseEXDialog = true;
            printDialog1.AllowSomePages = true;
            printDialog1.AllowCurrentPage = true;
            printDialog1.AllowPrintToFile = false;

            printDialog1.PrinterSettings.MinimumPage = 1;
            printDialog1.PrinterSettings.MaximumPage = totalPageCount;

            if(printDialog1.PrinterSettings.FromPage == 0) {
                printDialog1.PrinterSettings.FromPage = printDialog1.PrinterSettings.MinimumPage;
            }

            if(printDialog1.PrinterSettings.ToPage == 0) {
                printDialog1.PrinterSettings.ToPage = printDialog1.PrinterSettings.MaximumPage;
            }

            DialogResult printDialogResult = printDialog1.ShowDialog();

            if(printDialogResult == DialogResult.OK) {
                if(printDialog1.PrinterSettings.Collate) {
                    //部単位で複数印刷
                    copiesParPage = 1;
                    copyTimes = 1;

                    for(var i = 0; i < printDialog1.PrinterSettings.Copies; i++) {
                        PrintProcess.setFirstPage();
                        paperPrinting = true;
                        tempPageCount = 0;
                        printDocument1.Print();
                    }
                }
                else {
                    //ページごとに複数印刷
                    copiesParPage = printDialog1.PrinterSettings.Copies;
                    copyTimes = copiesParPage;

                    PrintProcess.setFirstPage();
                    paperPrinting = true;
                    tempPageCount = 0;
                    printDocument1.Print();
                }
            }
        }




        //ページ設定
        private void setPrintArea() {
            PrintArea.landscape = printDocument1.DefaultPageSettings.Landscape;
            PrintArea.paperSizeHSet = printDocument1.DefaultPageSettings.PaperSize.Width;
            PrintArea.paperSizeWSet = printDocument1.DefaultPageSettings.PaperSize.Height;
            PrintArea.marginL = printDocument1.DefaultPageSettings.Margins.Left;
            PrintArea.marginR = printDocument1.DefaultPageSettings.Margins.Right;
            PrintArea.marginT = printDocument1.DefaultPageSettings.Margins.Top;
            PrintArea.marginB = printDocument1.DefaultPageSettings.Margins.Bottom;
        }




        //プレビュー領域の描写
        protected void makePreview() {
            PrintProcess.setFirstPage();
            paperPrinting = false;
            totalPageCount = 0;
            tempPageCount = 0;
            printPreviewControl1.Document = printDocument1;
            printPreviewControl1.UseAntiAlias = true;
        }




        //プレビュー領域のズーム
        private void previewZoom(bool autoZoom = true, int zoom = 100) {
            double zoomdouble;

            if(autoZoom) {
                double previewSizeH = printPreviewControl1.Height;
                double previewSizeW = printPreviewControl1.Width;

                double zoomdoubleH = (previewSizeH / 96 * 100 * 0.95) / PrintArea.paperSizeH;
                double zoomdoubleW = (previewSizeW / 96 * 100 * 0.95) / PrintArea.paperSizeW;

                zoomdouble = (zoomdoubleH < zoomdoubleW) ? zoomdoubleH : zoomdoubleW;

                zoomLevel = (decimal)(zoomLevelSet.Length + 0.5);

                for(int i = 0; i < zoomLevelSet.Length; i++) {
                    if(zoomdouble * 100 < zoomLevelSet[i]) {
                        zoomLevel = (decimal)(i - 0.5);
                        break;
                    }
                }

                if(zoomLevel <= 0) {
                    button6.Enabled = false;
                }
                else {
                    button6.Enabled = true;
                }

                if(zoomLevel >= zoomLevelSet.Length - 1) {
                    button7.Enabled = false;
                }
                else {
                    button7.Enabled = true;
                }
            }
            else {
                zoomdouble = (double)zoom / 100;
            }

            printPreviewControl1.AutoZoom = false;
            printPreviewControl1.Zoom = zoomdouble;
            label1.Text = string.Format("{0}%", ((int)(zoomdouble * 100)).ToString());
        }




        //全体ボタンクリックイベント
        private void button4_Click(object sender, EventArgs e) {
            previewZoom(true);
        }




        //等倍ボタンクリックイベント
        private void button5_Click(object sender, EventArgs e) {
            for(int i = 0; i < zoomLevelSet.Length; i++) {
                if(zoomLevelSet[i] >= 100) {
                    zoomLevel = (decimal)(i);
                    break;
                }
            }

            if(zoomLevel <= 0) {
                button6.Enabled = false;
            }
            else {
                button6.Enabled = true;
            }

            if(zoomLevel >= zoomLevelSet.Length - 1) {
                button7.Enabled = false;
            }
            else {
                button7.Enabled = true;
            }

            previewZoom(false, 100);
        }




        //ズームアウトボタンクリックイベント
        private void button6_Click(object sender, EventArgs e) {
            if(Math.Abs(zoomLevel % 1) > 0) {
                zoomLevel = Math.Floor(zoomLevel);
            }
            else {
                zoomLevel--;
            }

            if(zoomLevel <= 0) {
                button6.Enabled = false;
            }
            else {
                button6.Enabled = true;
            }

            if(zoomLevel >= zoomLevelSet.Length - 1) {
                button7.Enabled = false;
            }
            else {
                button7.Enabled = true;
            }

            previewZoom(false, zoomLevelSet[(int)zoomLevel]);
        }




        //ズームインボタンクリックイベント
        private void button7_Click(object sender, EventArgs e) {
            if(Math.Abs(zoomLevel % 1) > 0) {
                zoomLevel = Math.Ceiling(zoomLevel);
            }
            else {
                zoomLevel++;
            }

            if(zoomLevel <= 0) {
                button6.Enabled = false;
            }
            else {
                button6.Enabled = true;
            }

            if(zoomLevel >= zoomLevelSet.Length - 1) {
                button7.Enabled = false;
            }
            else {
                button7.Enabled = true;
            }

            previewZoom(false, zoomLevelSet[(int)zoomLevel]);
        }




        //ページ戻るボタンクリックイベント
        private void button8_Click(object sender, EventArgs e) {
            viewPage--;

            if(viewPage <= 1) {
                button8.Enabled = false;
            }

            printPreviewControl1.StartPage = viewPage - 1;
            label2.Text = string.Format("{0}/{1}", viewPage, totalPageCount);
            button9.Enabled = true;
        }




        //ページ進むボタンクリックイベント
        private void button9_Click(object sender, EventArgs e) {
            viewPage++;

            if(viewPage >= totalPageCount) {
                button9.Enabled = false;
            }

            printPreviewControl1.StartPage = viewPage - 1;
            label2.Text = string.Format("{0}/{1}", viewPage, totalPageCount);
            button8.Enabled = true;
        }




        //閉じるボタンクリックイベント
        private void button1_Click(object sender, EventArgs e) {
            this.Close();
        }




        //印刷ページ生成（1ページごとに呼び出される）
        private void printDocumentPrintPage(object sender, PrintPageEventArgs e) {
            if(paperPrinting) {
                //印刷時の動作
                int fromPage = 0;
                int toPage = 0;

                if(e.PageSettings.PrinterSettings.PrintRange == PrintRange.SomePages) {
                    //印刷範囲ページ指定
                    fromPage = e.PageSettings.PrinterSettings.FromPage;
                    toPage = e.PageSettings.PrinterSettings.ToPage;
                }
                else if(e.PageSettings.PrinterSettings.PrintRange == PrintRange.CurrentPage) {
                    //印刷範囲現在のページ
                    fromPage = viewPage;
                    toPage = viewPage;
                }
                else {
                    //印刷範囲すべてのページ
                    fromPage = 1;
                    toPage = totalPageCount;
                }

                if(tempPageCount == 0) {
                    //プリンタのハードマージンを取得
                    PrintArea.hardMarginX = e.PageSettings.HardMarginX;
                    PrintArea.hardMarginY = e.PageSettings.HardMarginY;
                }

                for(int i = tempPageCount + 1; i < fromPage; i++) {
                    //印刷対象ページまでダミーの印刷
                    tempPageCount++;

                    PrintProcess.goPrint(e);
                    e.Graphics.Clear(Color.White);
                    e.Graphics.TranslateTransform(-PrintArea.printerMarginLmm, -PrintArea.printerMarginTmm);
                }

                //プリンタへ実際の印刷
                tempPageCount++;

                bool hasMorePages = false;
                bool sameFrontPage;

                if(copyTimes > 1) {
                    sameFrontPage = true;
                    hasMorePages = PrintProcess.goPrint(e, sameFrontPage);
                    tempPageCount--;
                    copyTimes--;
                }
                else {
                    sameFrontPage = false;
                    hasMorePages = PrintProcess.goPrint(e);
                    copyTimes = copiesParPage;
                }

                if(sameFrontPage) {
                    e.HasMorePages = true;
                }
                else if(tempPageCount < toPage && hasMorePages) {
                    e.HasMorePages = true;
                }
                else {
                    e.HasMorePages = false;
                }
            }
            else {
                //プレビュー時の動作
                totalPageCount++;

                if(tempPageCount == 0) {
                    //プレビュー時はハードマージンを0に
                    PrintArea.hardMarginX = 0;
                    PrintArea.hardMarginY = 0;
                }

                bool hasMorePages = PrintProcess.goPrint(e);

                if(hasMorePages) {
                    e.HasMorePages = true;
                }
                else {
                    e.HasMorePages = false;
                }

                if(!e.HasMorePages) {
                    if(totalPageCount < 2) {
                        button9.Enabled = false;
                    }
                    else {
                        button9.Enabled = true;
                    }

                    label2.Text = string.Format("{0}/{1}", viewPage, totalPageCount);
                }
            }
        }

    }
}
