// 下水データ管理システム
// 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.Collections.Generic;
using System.Data.SQLite;
using System.Drawing;
using System.Windows.Forms;

namespace WindowsFormsApplication1 {
    public partial class Form5SettingViewDataPreMake :Form {
        public Form5SettingViewDataPreMake() {
            InitializeComponent();
        }


        TabControl tabControl1 = new TabControlEx();

        List<ColumnConfig> ccSet = ColumnsConfigSet.getSet;
        List<string> inputTabTitle = InputTab.title;

        int place = 4;
        Panel[] putPlace;
        int[] placeCount;

        public DataGridView dgv { get; set; }
        public bool preMake { get; set; }
        public bool changed { get; set; }

        public FormA1OpeningSplash winSplash { get; set; }




        //ロード時イベント
        private void Form5SettingViewDataPreMake_Load(object sender, EventArgs e) {
            this.SuspendLayout();

            if(preMake) {
                //プログラム起動時のフォーム事前生成
                this.Visible = false;

                makeInputForm();

                this.Close();
            }
            else {
                //変更時のフォーム状態セット
                setInputForm();

                tabControl1.SelectedIndex = 0;
                tabControl1.Size = new Size(992, 551);
                this.ActiveControl = button2;
            }

            this.ResumeLayout();
        }




        //入力フォーム生成
        private void makeInputForm() {
            //パネル生成
            putPlace = new Panel[(inputTabTitle.Count + 1) * 10 + place];
            placeCount = new int[(inputTabTitle.Count + 1) * 10 + place];

            tabControl1.Anchor = (AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right);
            tabControl1.Location = new Point(9, 42);
            tabControl1.Size = new Size(992, 511);
            tabControl1.SizeMode = TabSizeMode.Fixed;
            tabControl1.Multiline = true;
            tabControl1.ItemSize = new Size(73, 19);
            tabControl1.Appearance = TabAppearance.FlatButtons;

            this.Controls.Add(tabControl1);

            for(int i = 0; i < inputTabTitle.Count; i++) {
                for(int j = 0; j < 4; j++) {
                    Panel newPanel = new Panel();
                    newPanel.AutoSize = true;
                    newPanel.Location = new Point(j * 242 + 5, 5);
                    newPanel.Name = "panel" + (i + 1).ToString() + (j + 1).ToString();
                    newPanel.BorderStyle = BorderStyle.None;

                    putPlace[(i + 1) * 10 + j + 1] = newPanel;
                    placeCount[(i + 1) * 10 + j + 1] = 0;
                }
            }

            //コントロール配置
            int pitchY = 27;
            int offsetY = 8;
            int ccNo = 0;
            int ccTotal = dgv.ColumnCount;
            decimal stepPer100 = 100M / ccTotal;
            decimal setpIntegrate = 0;

            foreach(ColumnConfig cc in ccSet) {
                ccNo++;
                setpIntegrate += stepPer100;

                if(setpIntegrate >= 10) {
                    winSplash.ProgressMessage = "表示データ設定フォーム生成中（" + (Math.Round((decimal)ccNo / ccTotal * 10M, 0) * 10).ToString() + "%）";
                    Application.DoEvents();
                    setpIntegrate = 0;
                }

                if(cc.Name == "id" || cc.Name == "del_flg" || cc.Name == "kanrisya" || cc.Name == "syorijou" || cc.Name == "sokutei_dt") {
                    continue;
                }

                int ccIndex = ColumnsConfigSet.nameToIndex(cc.Name);
                int putPlaceNo = ccSet[ccIndex].putPlaceNo;

                if(putPlaceNo < 0) {
                    putPlaceNo = 14;
                }

                CheckBox newCheckBox = new CheckBox();
                newCheckBox.Name = cc.Name;
                newCheckBox.Size = new Size(20, 20);
                newCheckBox.Location = new Point(158, placeCount[putPlaceNo] * pitchY + offsetY + 1);
                newCheckBox.Checked = cc.Visible;

                putPlace[putPlaceNo].Controls.Add(newCheckBox);

                Label newLabel = new Label();
                newLabel.Name = "tl_" + cc.Name;
                newLabel.Text = cc.HeaderText + ccSet[ccIndex].unit;
                newLabel.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                newLabel.AutoSize = true;
                newLabel.Location = new Point(0, placeCount[putPlaceNo] * pitchY + offsetY + 3);
                newLabel.TextAlign = ContentAlignment.MiddleLeft;

                putPlace[putPlaceNo].Controls.Add(newLabel);

                placeCount[putPlaceNo]++;
            }

            //タブ生成、パネル配置
            for(int i = 0; i < inputTabTitle.Count; i++) {
                TabPage newTabPage = new TabPage();
                newTabPage.Text = inputTabTitle[i];
                newTabPage.BorderStyle = BorderStyle.None;
                newTabPage.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                newTabPage.BackColor = Color.WhiteSmoke;
                newTabPage.AutoScroll = true;

                for(int j = 0; j < 4; j++) {
                    newTabPage.Controls.Add(putPlace[(i + 1) * 10 + j + 1]);
                }

                tabControl1.Controls.Add(newTabPage);
            }
        }




        //入力フォーム状態セット
        private void setInputForm() {
            this.SuspendLayout();

            foreach(DataGridViewColumn column in dgv.Columns) {
                if(column.Name == "id" || column.Name == "del_flg" || column.Name == "kanrisya" || column.Name == "syorijou" || column.Name == "sokutei_dt") {
                    continue;
                }

                int ccIndex = ColumnsConfigSet.nameToIndex(column.Name);
                int putPlaceNo = ccSet[ccIndex].putPlaceNo;

                if(putPlaceNo < 0) {
                    putPlaceNo = 14;
                }

                ((CheckBox)putPlace[putPlaceNo].Controls[column.Name]).Checked = column.Visible;
            }

            this.ResumeLayout();
        }




        //設定するボタンクリックイベント
        private void button1_Click(object sender, EventArgs e) {
            FunctionForDatabase.setSuishitsuKanriRow();
            string dbTransactionCmd = "";

            FormA2ProgressSplash progressSplash1 = new FormA2ProgressSplash();
            progressSplash1.Owner = this;
            progressSplash1.Show();
            progressSplash1.Refresh();

            int ccNo = 0;
            int ccTotal = dgv.ColumnCount;
            decimal stepPer100 = 100M / ccTotal;
            decimal setpIntegrate = 0;

            foreach(DataGridViewColumn column in dgv.Columns) {
                ccNo++;
                setpIntegrate += stepPer100;

                if(setpIntegrate >= 10) {
                    progressSplash1.ProgressMessage = "表示データ設定保存中（" + (Math.Round((decimal)ccNo / ccTotal * 10M, 0) * 10).ToString() + "%）";
                    Application.DoEvents();
                    setpIntegrate = 0;
                }

                if(column.Name == "id" || column.Name == "del_flg" || column.Name == "kanrisya" || column.Name == "syorijou" || column.Name == "sokutei_dt") {
                    continue;
                }

                dbTransactionCmd += "UPDATE suishitsu_kanri_setting SET visible=";

                int ccIndex = ColumnsConfigSet.nameToIndex(column.Name);
                int putPlaceNo = ccSet[ccIndex].putPlaceNo;

                if(putPlaceNo < 0) {
                    putPlaceNo = 14;
                }

                if(((CheckBox)putPlace[putPlaceNo].Controls[column.Name]).Checked) {
                    dbTransactionCmd += "1";
                }
                else {
                    dbTransactionCmd += "0";
                }

                dbTransactionCmd += " WHERE column_name='" + column.Name + "';";
            }

            if(dbTransactionCmd != "") {
                using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                    con.Open();

                    using(var transaction = con.BeginTransaction()) {
                        try {
                            using(var cmd = con.CreateCommand()) {
                                cmd.CommandText = dbTransactionCmd;
                                cmd.ExecuteNonQuery();
                            }

                            transaction.Commit();
                        }
                        catch(Exception ex) {
                            transaction.Rollback();
                            MessageBox.Show(ex.Message);
                        }
                    }
                }
            }

            progressSplash1.Close();
            progressSplash1.Dispose();
            this.Activate();

            changed = true;
            this.Close();
        }




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