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

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


        Color validationOK = Color.FromArgb(225, 225, 225);

        string zeroSTR = "0";

        public string kanrisya { get; set; }
        public string syorijou { get; set; }
        public bool changed { get; set; }




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

            changed = false;

            makeInputForm();
            dataGridViewInitialize();
            writeReference();
            setInputForm();

            this.ActiveControl = button2;

            this.ResumeLayout();
        }




        //入力フォーム生成
        private void makeInputForm() {
            //コントロール配置
            Label labelKanrisya = new Label();
            labelKanrisya.Name = "labelKanrisya";
            labelKanrisya.Text = "対象の管理者：" + kanrisya;
            labelKanrisya.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
            labelKanrisya.AutoSize = true;
            labelKanrisya.Location = new Point(5, 50);
            labelKanrisya.TextAlign = ContentAlignment.MiddleLeft;
            this.Controls.Add(labelKanrisya);

            Label labelSyorijou = new Label();
            labelSyorijou.Name = "labelSyorijou";
            labelSyorijou.Text = "対象の処理場：" + syorijou;
            labelSyorijou.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
            labelSyorijou.AutoSize = true;
            labelSyorijou.Location = new Point(5, 77);
            labelSyorijou.TextAlign = ContentAlignment.MiddleLeft;
            this.Controls.Add(labelSyorijou);

            int pitchY = 27;
            int offsetY = 104;

            for(int i = 0; i < 3; i++) {
                Label newLabel = new Label();
                newLabel.Name = "tl_d" + i.ToString();

                string dayName;

                if(i == 0) {
                    dayName = "当日";
                }
                else {
                    dayName = i.ToString() + "日前";
                }

                newLabel.Text = "これ以上の場合は雨天とする雨量[mm](" + dayName +")";
                newLabel.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                newLabel.AutoSize = true;
                newLabel.Location = new Point(5, i * pitchY + offsetY + 3);
                newLabel.TextAlign = ContentAlignment.MiddleLeft;
                this.Controls.Add(newLabel);

                NumericUpDownEx newNumericUpDown = new NumericUpDownEx();
                newNumericUpDown.Name = "nud_d" + i.ToString();
                newNumericUpDown.Font = new Font("Meiryo UI", 9F, FontStyle.Regular, GraphicsUnit.Point, ((byte)(128)));
                newNumericUpDown.Size = new Size(65, 21);
                newNumericUpDown.Location = new Point(259, i * pitchY + offsetY + 3);
                newNumericUpDown.BorderStyle = BorderStyle.None;
                newNumericUpDown.BackColor = Color.White;
                newNumericUpDown.TextAlign = HorizontalAlignment.Right;

                string ccFormat = ColumnsConfigSet.nameToFormat("uryou");

                if(ccFormat == "N0") {
                    newNumericUpDown.DecimalPlaces = 0;
                    newNumericUpDown.Increment = 1M;
                    zeroSTR = "0";
                }
                else if(ccFormat == "N1") {
                    newNumericUpDown.DecimalPlaces = 1;
                    newNumericUpDown.Increment = 0.1M;
                    zeroSTR = "0.0";
                }
                else if(ccFormat == "N2") {
                    newNumericUpDown.DecimalPlaces = 2;
                    newNumericUpDown.Increment = 0.01M;
                    zeroSTR = "0.00";
                }
                else if(ccFormat == "N3") {
                    newNumericUpDown.DecimalPlaces = 3;
                    newNumericUpDown.Increment = 0.001M;
                    zeroSTR = "0.000";
                }
                else if(ccFormat == "N4") {
                    newNumericUpDown.DecimalPlaces = 4;
                    newNumericUpDown.Increment = 0.0001M;
                    zeroSTR = "0.0000";
                }
                else if(ccFormat == "N5") {
                    newNumericUpDown.DecimalPlaces = 5;
                    newNumericUpDown.Increment = 0.00001M;
                    zeroSTR = "0.00000";
                }

                newNumericUpDown.Maximum = ColumnsConfigSet.getSet[ColumnsConfigSet.nameToIndex("uryou")].Maximum;
                newNumericUpDown.Minimum = ColumnsConfigSet.getSet[ColumnsConfigSet.nameToIndex("uryou")].Minimum;

                ((TextBox)newNumericUpDown.Controls[1]).Text = null;

                newNumericUpDown.Click += new EventHandler(numericUpDownAllFocus);
                newNumericUpDown.GotFocus += new EventHandler(numericUpDownAllFocus);
                newNumericUpDown.ValueChanged += new EventHandler((sender, args) => numericUpDownChanged(ccFormat, sender, args));
                newNumericUpDown.Leave += new EventHandler((sender, args) => numericUpDownChanged(ccFormat, sender, args));

                this.Controls.Add(newNumericUpDown);

                Label newValidationLabel = new Label();
                newValidationLabel.Name = "vl_d" + i.ToString();
                newValidationLabel.Size = new Size(6, 21);
                newValidationLabel.Location = new Point(323, i * pitchY + offsetY + 1);
                newValidationLabel.Padding = new Padding(0, 0, 0, 0);
                newValidationLabel.BackColor = validationOK;
                newValidationLabel.Text = "";
                this.Controls.Add(newValidationLabel);

                Label borderLabel = new Label();
                borderLabel.Name = "bl_d" + i.ToString();
                borderLabel.Size = new Size(72, 23);
                borderLabel.Location = new Point(newNumericUpDown.Location.X - 1, newNumericUpDown.Location.Y - 3);
                borderLabel.BorderStyle = BorderStyle.FixedSingle;
                borderLabel.BackColor = Color.White;
                this.Controls.Add(borderLabel);
            }
        }




        //dataGridView1準備
        private void dataGridViewInitialize() {
            //DataGirdViewのプロパティDoubleBufferedをtrueに設定
            Type dataGridViewType = typeof(DataGridView);
            PropertyInfo dataGridViewProperty = dataGridViewType.GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);
            dataGridViewProperty.SetValue(dataGridView1, true, null);
            dataGridView1.EnableHeadersVisualStyles = false;

            //列作成
            DataGridViewTextBoxColumn c1 = new DataGridViewTextBoxColumn();
            c1 = new DataGridViewTextBoxColumn();
            c1.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            c1.Resizable = DataGridViewTriState.False;
            c1.ReadOnly = true;
            c1.HeaderText = "管理者";
            c1.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            c1.Name = "kanrisya";
            c1.SortMode = DataGridViewColumnSortMode.NotSortable;
            c1.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            c1.DefaultCellStyle.NullValue = null;
            c1.Width = 115;
            dataGridView1.Columns.Add(c1);

            DataGridViewTextBoxColumn c2 = new DataGridViewTextBoxColumn();
            c2 = new DataGridViewTextBoxColumn();
            c2.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            c2.Resizable = DataGridViewTriState.False;
            c2.ReadOnly = true;
            c2.HeaderText = "処理場";
            c2.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
            c2.Name = "syorijou";
            c2.SortMode = DataGridViewColumnSortMode.NotSortable;
            c2.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
            c2.DefaultCellStyle.NullValue = null;
            c2.Width = 155;
            dataGridView1.Columns.Add(c2);

            for(int i = 0; i < 3; i++) {
                string dayName;

                if(i == 0) {
                    dayName = "当日";
                }
                else {
                    dayName = i.ToString() + "日前";
                }

                DataGridViewTextBoxColumn newColumn = new DataGridViewTextBoxColumn();
                newColumn = new DataGridViewTextBoxColumn();
                newColumn.AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
                newColumn.Resizable = DataGridViewTriState.False;
                newColumn.ReadOnly = true;
                newColumn.HeaderText = "雨天条件\r\n(" + dayName + ")";
                newColumn.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
                newColumn.Name = "lluryouDay" + i.ToString();
                newColumn.SortMode = DataGridViewColumnSortMode.NotSortable;
                newColumn.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
                newColumn.DefaultCellStyle.NullValue = null;
                newColumn.Width = 65;
                dataGridView1.Columns.Add(newColumn);
            }
        }




        //参考欄の記入
        private void writeReference() {
            dataGridView1.Rows.Add(new string[] { "(標準)", "", "1.0", "15.0", "30.0" });

            foreach(SeitenConfig sc in SeitenConfigSet.getSet) {
                dataGridView1.Rows.Add(new string[] { sc.kanrisya, sc.syorijou, sc.utenLLUryouDay0.ToString(), sc.utenLLUryouDay1.ToString(), sc.utenLLUryouDay2.ToString() });
            }
        }




        //入力フォーム状態セット
        private void setInputForm() {
            if(SeitenConfigSet.getUtenLLUryouDay0(kanrisya, syorijou) != null) {
                if((decimal)SeitenConfigSet.getUtenLLUryouDay0(kanrisya, syorijou) == 0) {
                    ((TextBox)this.Controls["nud_d0"].Controls[1]).Text = zeroSTR;
                }
                else {
                    ((NumericUpDownEx)this.Controls["nud_d0"]).Value = (decimal)SeitenConfigSet.getUtenLLUryouDay0(kanrisya, syorijou);
                }
            }
            else {
                ((TextBox)this.Controls["nud_d0"].Controls[1]).Text = null;
            }

            if(SeitenConfigSet.getUtenLLUryouDay1(kanrisya, syorijou) != null) {
                if((decimal)SeitenConfigSet.getUtenLLUryouDay1(kanrisya, syorijou) == 0) {
                    ((TextBox)this.Controls["nud_d1"].Controls[1]).Text = zeroSTR;
                }
                else {
                    ((NumericUpDownEx)this.Controls["nud_d1"]).Value = (decimal)SeitenConfigSet.getUtenLLUryouDay1(kanrisya, syorijou);
                }
            }
            else {
                ((TextBox)this.Controls["nud_d1"].Controls[1]).Text = null;
            }

            if(SeitenConfigSet.getUtenLLUryouDay2(kanrisya, syorijou) != null) {
                if((decimal)SeitenConfigSet.getUtenLLUryouDay2(kanrisya, syorijou) == 0) {
                    ((TextBox)this.Controls["nud_d2"].Controls[1]).Text = zeroSTR;
                }
                else {
                    ((NumericUpDownEx)this.Controls["nud_d2"]).Value = (decimal)SeitenConfigSet.getUtenLLUryouDay2(kanrisya, syorijou);
                }
            }
            else {
                ((TextBox)this.Controls["nud_d2"].Controls[1]).Text = null;
            }
        }




        //NumericUpDownフォーカス時に数字を選択状態にする
        private void numericUpDownAllFocus(object sender, EventArgs e) {
            NumericUpDown n = (NumericUpDown)sender;
            int NumberLength = ((TextBox)n.Controls[1]).TextLength;
            ((TextBox)n.Controls[1]).Select(0, NumberLength);
        }




        //選択された場合に選択状態を解除する
        private void dataGridView1_SelectionChanged(object sender, EventArgs e) {
            dataGridView1.Rows[dataGridView1.CurrentCell.RowIndex].Selected = false;
        }




        //NumericUpDown値変更時のイベント
        private void numericUpDownChanged(string format, object sender, EventArgs e) {
            //データごとの規定の小数点以下桁数に切捨て
            NumericUpDown n = (NumericUpDownEx)sender;

            if(format == "N0") {
                n.Value = Math.Truncate(n.Value);
            }
            else if(format == "N1") {
                n.Value = Math.Truncate(n.Value * 10) / 10;
            }
            else if(format == "N2") {
                n.Value = Math.Truncate(n.Value * 100) / 100;
            }
            else if(format == "N3") {
                n.Value = Math.Truncate(n.Value * 1000) / 1000;
            }
            else if(format == "N4") {
                n.Value = Math.Truncate(n.Value * 10000) / 10000;
            }
            else if(format == "N5") {
                n.Value = Math.Truncate(n.Value * 100000) / 100000;
            }
        }




        //設定するボタンクリックイベント
        private void button1_Click(object sender, EventArgs e) {
            if(MessageBox.Show("設定を変更してよろしいですか\nこの処理場の晴天日は、過去も含めて全て新設定値で再判定されます", "", MessageBoxButtons.OKCancel) == DialogResult.Cancel) {
                return;
            }
            
            string ccFormat = ColumnsConfigSet.nameToFormat("uryou");

            NumericUpDown settedNumericUpDown0 = (NumericUpDownEx)this.Controls["nud_d0"];
            decimal? uten_ll_uryou_day0 = null;

            if(!String.IsNullOrEmpty(((TextBox)settedNumericUpDown0.Controls[1]).Text)) {
                uten_ll_uryou_day0 = FunctionForDatabase.decConvForDB(settedNumericUpDown0.Value, ccFormat);
            }

            NumericUpDown settedNumericUpDown1 = (NumericUpDownEx)this.Controls["nud_d1"];
            decimal? uten_ll_uryou_day1 = null;

            if(!String.IsNullOrEmpty(((TextBox)settedNumericUpDown1.Controls[1]).Text)) {
                uten_ll_uryou_day1 = FunctionForDatabase.decConvForDB(settedNumericUpDown1.Value, ccFormat);
            }

            NumericUpDown settedNumericUpDown2 = (NumericUpDownEx)this.Controls["nud_d2"];
            decimal? uten_ll_uryou_day2 = null;

            if(!String.IsNullOrEmpty(((TextBox)settedNumericUpDown2.Controls[1]).Text)) {
                uten_ll_uryou_day2 = FunctionForDatabase.decConvForDB(settedNumericUpDown2.Value, ccFormat);
            }

            int changedColumnNo = 0;

            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                //最初にUPDATEを試行
                try {
                    using(var cmd = con.CreateCommand()) {
                        string sql1 = "UPDATE uten_judge_uryou_setting SET ";
                        string sql2 = "uten_ll_uryou_day0 = @uten_ll_uryou_day0, uten_ll_uryou_day1 = @uten_ll_uryou_day1, uten_ll_uryou_day2 = @uten_ll_uryou_day2 ";
                        string sql3 = "WHERE kanrisya = @kanrisya AND syorijou = @syorijou;";

                        cmd.CommandText = sql1 + sql2 + sql3;

                        cmd.Parameters.Add(new SQLiteParameter("@kanrisya", kanrisya));
                        cmd.Parameters.Add(new SQLiteParameter("@syorijou", syorijou));
                        cmd.Parameters.Add(new SQLiteParameter("@uten_ll_uryou_day0", uten_ll_uryou_day0));
                        cmd.Parameters.Add(new SQLiteParameter("@uten_ll_uryou_day1", uten_ll_uryou_day1));
                        cmd.Parameters.Add(new SQLiteParameter("@uten_ll_uryou_day2", uten_ll_uryou_day2));

                        cmd.ExecuteNonQuery();
                    }

                    using(var cmd = con.CreateCommand()) {
                        cmd.CommandText = "SELECT CHANGES();";

                        using(var reader = cmd.ExecuteReader()) {
                            while(reader.Read()) {
                                changedColumnNo = reader.GetInt32(0);
                            }
                        }
                    }
                }
                catch(Exception ex) {
                    MessageBox.Show(ex.Message);
                }

                if(changedColumnNo == 0) {
                    //UPDATEで更新件数が0の場合INSERT
                    try {
                        using(var cmd = con.CreateCommand()) {
                            string sql1 = "INSERT INTO uten_judge_uryou_setting(";
                            string sql2 = "kanrisya, syorijou, uten_ll_uryou_day0, uten_ll_uryou_day1, uten_ll_uryou_day2";
                            string sql3 = ") VALUES(";
                            string sql4 = "@kanrisya, @syorijou, @uten_ll_uryou_day0, @uten_ll_uryou_day1, @uten_ll_uryou_day2";
                            string sql5 = ");";

                            cmd.CommandText = sql1 + sql2 + sql3 + sql4 + sql5;

                            cmd.Parameters.Add(new SQLiteParameter("@kanrisya", kanrisya));
                            cmd.Parameters.Add(new SQLiteParameter("@syorijou", syorijou));
                            cmd.Parameters.Add(new SQLiteParameter("@uten_ll_uryou_day0", uten_ll_uryou_day0));
                            cmd.Parameters.Add(new SQLiteParameter("@uten_ll_uryou_day1", uten_ll_uryou_day1));
                            cmd.Parameters.Add(new SQLiteParameter("@uten_ll_uryou_day2", uten_ll_uryou_day2));

                            cmd.ExecuteNonQuery();
                        }
                    }
                    catch(Exception ex) {
                        MessageBox.Show(ex.Message);
                    }
                }

                con.Close();
            }

            //晴天日設定用リストのリフレッシュ
            SeitenConfigSet.presetSeitenConfigSet();

            changed = true;

            this.Close();
        }




        //削除ボタンクリックイベント
        private void button3_Click(object sender, EventArgs e) {
            if(MessageBox.Show("設定を削除してよろしいですか\n削除した場合、晴天日は過去も含めて全て標準値で再判定されます", "", MessageBoxButtons.OKCancel) == DialogResult.Cancel) {
                return;
            }

            using(var con = new SQLiteConnection(DataBaseConfig.ConnectionString)) {
                con.Open();

                try {
                    using(var cmd = con.CreateCommand()) {
                        string sql1 = "DELETE FROM uten_judge_uryou_setting WHERE kanrisya = @kanrisya AND syorijou = @syorijou;";

                        cmd.CommandText = sql1;

                        cmd.Parameters.Add(new SQLiteParameter("@kanrisya", kanrisya));
                        cmd.Parameters.Add(new SQLiteParameter("@syorijou", syorijou));

                        cmd.ExecuteNonQuery();
                    }
                }
                catch(Exception ex) {
                    MessageBox.Show(ex.Message);
                }

                con.Close();
            }

            //晴天日設定用リストのリフレッシュ
            SeitenConfigSet.presetSeitenConfigSet();

            changed = true;

            this.Close();
        }




        //キャンセルボタンクリックイベント
        private void button2_Click(object sender, EventArgs e) {
            this.Close();
        }

    }
}
