using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace 電子文書回覧監視ツール {
    public partial class Folder : Form {
        public Form1 form1;
        public Folder(Form1 form1) {
            InitializeComponent();
            this.form1 = form1;
            sc = new soundcontrol(this);
            //復元
            if(this.form1.getLoadData("folderInfo") != null) {
                txtマスク.Text = this.form1.getLoadData("folderInfo").Rows[0][0].ToString();
                txtNotマスク.Text = this.form1.getLoadData("folderInfo").Rows[0][1].ToString();
                chkBeepON.Checked = (this.form1.getLoadData("folderInfo").Rows[0][2].ToString() == "True") ? true : false;
            }

        }

        soundcontrol sc;
        string replacestrings;
        static public string parameterFolder = "";
        public bool beepON = false;

        //終了時に呼ばれる
        public DataTable getSaveTable() {
            DataTable dt = new DataTable("folderInfo");
            dt.Columns.Add();
            dt.Columns.Add();
            dt.Columns.Add();
            dt.Rows.Add(txtマスク.Text, txtNotマスク.Text, chkBeepON.Checked.ToString());
            return dt;
        }


        public void 構成入手(ref List<string> servers, ref int serverport, ref int watchport, ref int trackPort, ref List<string> networks) {
            DataSet datasetcommon;
            if(!form1.MODE2) {
                datasetcommon = CommonParameter.read();
            }
            else {
                //MODE2
                datasetcommon = CommonParameter.readCache();
            }
            lblキャッシュmsg.Text = CommonParameter.message;

            //server = datasetcommon.Tables["構成"].Rows[0]["管理サーバ"].ToString();
            serverport = Convert.ToInt32(datasetcommon.Tables["構成"].Rows[0]["ポート"]);
            trackPort = Convert.ToInt32(datasetcommon.Tables["構成"].Rows[1]["ポート"]);
            watchport = Convert.ToInt32(datasetcommon.Tables["構成"].Rows[2]["ポート"]);
            for(int i = 0; i < datasetcommon.Tables["構成"].Rows.Count; i++) {
                if(datasetcommon.Tables["構成"].Rows[i]["ネットワーク"].ToString() != "") {
                    networks.Add(datasetcommon.Tables["構成"].Rows[i]["ネットワーク"].ToString());
                }
                if(datasetcommon.Tables["構成"].Rows[i]["管理サーバ"].ToString() != "") {
                    servers.Add(datasetcommon.Tables["構成"].Rows[i]["管理サーバ"].ToString());
                }
            }

            replacestrings = datasetcommon.Tables["構成"].Rows[0]["移行"].ToString();
            try {
                parameterFolder = datasetcommon.Tables["構成"].Rows[0]["パラメータフォルダ"].ToString();
                if(parameterFolder.Trim() == "") parameterFolder = System.AppDomain.CurrentDomain.BaseDirectory;
            }
            catch {
                parameterFolder = System.AppDomain.CurrentDomain.BaseDirectory;
            }
        }

        public bool パラメータ入手() {
            dataSet1.Clear();
            if(System.IO.File.Exists(parameterFolder + "parameter.xml")) {
                //パラメータ移行
                if(replacestrings != "") {
                    String buffer = System.IO.File.ReadAllText(parameterFolder + "parameter.xml", Encoding.UTF8);
                    buffer = buffer.ToUpper();
                    System.Text.RegularExpressions.Regex re = new System.Text.RegularExpressions.Regex("\r\n *</{0,1}XS:.*> *");
                    StringBuilder buffer3 = new StringBuilder(re.Replace(buffer, ""));
                    string 前 = replacestrings.Split(',')[0];
                    string 後 = replacestrings.Split(',')[1];
                    buffer3.Replace(前, 後);
                    System.IO.File.WriteAllText(parameterFolder + "parameter.xml", buffer3.ToString(), Encoding.UTF8);
                }
                //移行後再入力
                try {
                    dataSet1.ReadXml(parameterFolder + "parameter.xml", XmlReadMode.Auto);
                }
                catch(System.Xml.XmlException) {
                    if(MessageBox.Show("parameter.xmlはありますが空です。このまま続けますか？", "エラー", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) {
                        return false;
                    }
                }
            }
            else {
                if(MessageBox.Show("parameter.xmlが見つかりません。このまま続けますか？", "エラー", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.No) {
                    return false;
                }
            }
            //
            if(dataSet1.Tables["監視対象"] == null) {
                dataSet1.Tables.Add("監視対象");
                dataSet1.Tables["監視対象"].Columns.Add("文書種類");
                dataSet1.Tables["監視対象"].Columns.Add("ディレクトリ");
            }
            this.dataGridView1.DataSource = dataSet1.Tables["監視対象"];
            //
            if(this.form1.getLoadData("folderInfo") == null) {//暫定処置
                if(dataSet1.Tables["監視情報"] != null) {
                    txtマスク.Text = dataSet1.Tables["監視情報"].Rows[0][0].ToString();
                    if(dataSet1.Tables["監視情報"].Rows[0].ItemArray.Length == 3) {
                        txtNotマスク.Text = dataSet1.Tables["監視情報"].Rows[0][1].ToString();
                        //numUpDown1.Value = Convert.ToDecimal(dataSet1.Tables["監視情報"].Rows[0][2].ToString());
                    }
                    else {
                        dataSet1.Tables["監視情報"].Columns.Add("notmuskstring");
                        dataSet1.Tables["監視情報"].Columns.Add("beepnumber");
                        dataSet1.Tables["監視情報"].Rows[0][1] = "";
                        dataSet1.Tables["監視情報"].Rows[0][2] = "1";
                    }
                }
                else {
                    //監視情報の初期パラメータが無ければ作る
                    DataTable newtable = new DataTable("監視情報");
                    dataSet1.Tables.Add(newtable);
                    DataRow newrow = newtable.NewRow();
                    newtable.Rows.Add(newrow);
                    newtable.Columns.Add("muskstring");
                    newtable.Columns.Add("notmuskstring");
                    newtable.Columns.Add("beepnumber");
                    newrow[0] = "";
                    newrow[1] = "";
                    newrow[2] = "1";
                }
            }
            //
            form1.types.Clear();
            form1.folders.Clear();
            for(int i = 0; i < dataSet1.Tables["監視対象"].Rows.Count; i++) {
                form1.types.Add(dataSet1.Tables["監視対象"].Rows[i][0].ToString());
                form1.folders.Add(dataSet1.Tables["監視対象"].Rows[i][1].ToString().ToUpper());
            }
            form1.muskstring = txtマスク.Text;
            form1.notmuskstring = txtNotマスク.Text;

            dataSet1.AcceptChanges();

            return true;
        }

        public void パラメータ再入手() {
            form1.types.Clear();
            form1.folders.Clear();
            for(int i = 0; i < dataSet1.Tables["監視対象"].Rows.Count; i++) {
                form1.types.Add(dataSet1.Tables["監視対象"].Rows[i][0].ToString());
                form1.folders.Add(dataSet1.Tables["監視対象"].Rows[i][1].ToString().ToUpper());
            }
            form1.muskstring = this.txtマスク.Text;
            form1.notmuskstring = txtNotマスク.Text;
        }

        private void btn再読込_Click(object sender, EventArgs e) {
            dataSet1.Clear();
            dataSet1.ReadXml(parameterFolder + "parameter.xml");
            this.dataGridView1.DataSource = dataSet1.Tables["監視対象"];

            if(this.form1.getLoadData("folderInfo") == null) {//暫定処置
                if(dataSet1.Tables["監視情報"] != null) {
                    txtマスク.Text = dataSet1.Tables["監視情報"].Rows[0][0].ToString();
                    if(dataSet1.Tables["監視情報"].Rows[0].ItemArray.Length == 3) {
                        txtNotマスク.Text = dataSet1.Tables["監視情報"].Rows[0][1].ToString();
                        //numUpDown1.Value = Convert.ToDecimal(dataSet1.Tables["監視情報"].Rows[0][2].ToString());
                    }
                    else {
                        dataSet1.Tables["監視情報"].Columns.Add("notmuskstring");
                        dataSet1.Tables["監視情報"].Columns.Add("beepnumber");
                        dataSet1.Tables["監視情報"].Rows[0][1] = "";
                        dataSet1.Tables["監視情報"].Rows[0][2] = "1";
                    }
                }
                else {
                    //監視情報の初期パラメータが無ければ作る
                    DataTable newtable = new DataTable("監視情報");
                    dataSet1.Tables.Add(newtable);
                    DataRow newrow = newtable.NewRow();
                    newtable.Rows.Add(newrow);
                    newtable.Columns.Add("muskstring");
                    newtable.Columns.Add("notmuskstring");
                    newtable.Columns.Add("beepnumber");
                    newrow[0] = "";
                    newrow[1] = "";
                    newrow[2] = "1";
                }
            }
        }

        private void btn保存_Click(object sender, EventArgs e) {
            パラメタ保存();

        }

        private void パラメタ保存() {
            System.IO.StreamWriter strm = new System.IO.StreamWriter(parameterFolder + "parameter.xml", false, System.Text.Encoding.UTF8);
            dataSet1.WriteXml(strm);
            strm.Close();
            MessageBox.Show("パラメータを保存しました", " ", MessageBoxButtons.OK, MessageBoxIcon.None, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly);
            dataSet1.AcceptChanges();
            //this.BringToFront();
        }

        private void btn追加_Click(object sender, EventArgs e) {
            if(txt種類.Text == "" || txtパス.Text == "") {
                lblErrorMessage.Text = "資料種類名、またはパスが空白です";
                return;
            }
            DataTable t = dataSet1.Tables["監視対象"];
            for(int i = 0; i < t.Rows.Count; i++) {
                if(t.Rows[i][0].ToString().ToUpper() == txt種類.Text.ToUpper() || t.Rows[i][1].ToString().ToUpper() == txtパス.Text.ToUpper()) {
                    lblErrorMessage.Text = "資料種類名、またはパスのどちらかが既に登録されています";
                    return;
                }
            }
            lblErrorMessage.Text = "";
            DataRow r = t.NewRow();
            r[0] = this.txt種類.Text;
            r[1] = this.txtパス.Text;
            t.Rows.Add(r);
            txt種類.Clear();
            txtパス.Clear();

        }

        private void btn参照_Click(object sender, EventArgs e) {
            DialogResult result = folderBrowserDialog1.ShowDialog();
            if(result == System.Windows.Forms.DialogResult.OK) {
                txtパス.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        private void Folder_Load(object sender, EventArgs e) {
            lblErrorMessage.Text = "";
            txt種類.Text = txtパス.Text = "";
            if(form1.MODE2)
                lblmode2関連.Text = "（フルパスを指定します）";
            else
                lblmode2関連.Text = "（ネットワークドライブ文字はＮＧ）";

        }

        private void btn追加読込_Click(object sender, EventArgs e) {
            DialogResult result = openFileDialog1.ShowDialog();
            if(result == System.Windows.Forms.DialogResult.OK) {
                DataSet addset = new DataSet();
                addset.ReadXml(openFileDialog1.FileName);
                foreach(DataRow r in addset.Tables["監視対象"].Rows) {
                    Boolean skip = false;
                    foreach(DataRow row in dataSet1.Tables["監視対象"].Rows) {
                        if(r[0].ToString() == row[0].ToString() || r[1].ToString() == row[1].ToString()) {
                            skip = true; break;
                        }
                    }
                    if(skip) {
                        lblErrorMessage.Text = "重複したパラメータがありましたが、無視しました。";
                    }
                    else {
                        dataSet1.Tables["監視対象"].ImportRow(r);
                    }
                }
            }
        }

        private void btnSound_Click(object sender, EventArgs e) {
            sc.ShowDialog();
        }

        private void btn閉じる_Click(object sender, EventArgs e) {
            if(dataSet1.GetChanges() != null) {
                if(MessageBox.Show("パラメータが変更されています。保存しますか？", "確認", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) == DialogResult.Yes) {
                    パラメタ保存();
                }
            }
            dataSet1.AcceptChanges();
            this.Close();

        }

        private void chkBeepON_CheckedChanged(object sender, EventArgs e) {
            beepON = chkBeepON.Checked ? true : false;
        }

        private void 印刷PToolStripButton_Click(object sender, EventArgs e) {
            form1.FormPrint(this);
        }

        private void dataGridView1_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e) {
            if(MessageBox.Show("削除しますか？", "行の削除", MessageBoxButtons.YesNo) == DialogResult.No) {
                e.Cancel = true;     // 削除をキャンセル
            }
        }

        private void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e) {
            beforcell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
        }
        string beforcell;
        private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e) {
            
            string aftercell = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
            for(int rIdx = 0; rIdx < dataGridView1.Rows.Count; rIdx++) {
                if(aftercell == dataGridView1.Rows[rIdx].Cells[e.ColumnIndex].Value.ToString() && e.RowIndex != rIdx){
                    MessageBox.Show(string.Format("値「{0}」は他の行と重複しています。",aftercell));
                    dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value = beforcell;
                    return;
                }
            }
            
        }

        private void dataGridView1_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) {

        }

        private void txtパス_TextChanged(object sender, EventArgs e) {

        }
    }
}