using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;      // reg

namespace nodokaGuiEdit
{
    public partial class FormSetting : Form
    {
        public FormSetting()
        {
            InitializeComponent();
            // 行番号を書くコールバックルーチンの定義
            envList.RowPostPaint += new DataGridViewRowPostPaintEventHandler(putLineNumber);

            // ホームディレクトリ表示GridViewのフォント指定
            envList.ColumnHeadersDefaultCellStyle.Font = new Font("MS UI Gothic", 12);
            envList.DefaultCellStyle.Font = new Font("ＭＳ ゴシック", 12);
            envList.RowHeadersDefaultCellStyle.Font = new Font("MS UI Gothic", 12);


            this.envList.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;

            // Controlにデータを設定

            // 環境変数の値を取得して表示
            setEnvList("NODOKA", 1);
            setEnvList("HOME", 2);
            setEnvList("USERPROFILE", 2);
            setEnvList("HOMEDRIVE HOMEPATH", 3);
            setEnvList("のどか実行フォルダ", 4);

            // 以前の設定値を取り出して、各コントロールを設定

            RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software\\appletkan\\nodoka");
            int readData;

            // 終了時に位置を覚える
            readData = (int)rk.GetValue("b_position", 0);
            checkBox_position.Checked = (readData == 0) ? false : true;

            //ウィンドウサイズを覚える
            readData = (int)rk.GetValue("b_windowsize", 0);
            checkBox_windowsize.Checked = (readData == 0) ? false : true;

            //カラムサイズを覚える
            readData = (int)rk.GetValue("b_column", 0);
            checkBox_colum.Checked = (readData == 0) ? false : true;

            //フォントサイズを覚える
            readData = (int)rk.GetValue("b_fontsize", 0);
            checkBox_fontsize.Checked = (readData == 0) ? false : true;

            //予約語の強調表示
            readData = (int)rk.GetValue("b_bold", 0);
            checkBox_bold.Checked = (readData == 0) ? false : true;

            //ファイル名を上に表示する
            readData = (int)rk.GetValue("b_filename_caption", 0);
            checkBox_filename_caption.Checked = (readData == 0) ? false : true;

            //文字コード指定を覚える
            readData = (int)rk.GetValue("b_selectencode", 0);
            checkBox_selectencode.Checked = (readData == 0) ? false : true;
 
            // フォント名、フォントサイズ、フォントスタイル
            text_font.Text = (String)rk.GetValue("s_font", "ＭＳ ゴシック");
            text_fontsize.Text = rk.GetValue("i_fontsize", 10).ToString();

            String tmpFSname = (String)rk.GetValue("s_fontstyle", "Reguler");
            FontStyle tmpFS = FontStyle.Regular;
            text_fontstyle.Text = "標準";
            text_fontstyle_reg.Text = tmpFSname;

            if (tmpFSname.IndexOf("Bold") >= 0)
            {
                tmpFS = FontStyle.Bold;
                text_fontstyle.Text = "太字";
            }
            if (tmpFSname.IndexOf("Italic") >= 0)
            {
                tmpFS = FontStyle.Italic;
                text_fontstyle.Text = "斜体";
            }
            if (tmpFSname.IndexOf("Bold, Italic") >= 0)
            {
                tmpFS = FontStyle.Bold | FontStyle.Italic;
                text_fontstyle.Text = "太字 斜体";
            }

            text_font.Font = new Font(text_font.Text, 10, tmpFS);


            // 色を変える 1ならデフォルト
            readData = (int)rk.GetValue("b_color", 1);
            check_bcolor.Checked = (readData == 0) ? false : true;

            //色の取得
            button_color.ForeColor = Color.FromArgb((int)rk.GetValue("i_color", unchecked((int)(0xff000000))));                       // Color.Black
            button_backcolor.BackColor = Color.FromArgb((int)rk.GetValue("i_backcolor", unchecked((int)(0xffffffff))));               // Color.White
            button_backcolorAlt.BackColor = Color.FromArgb((int)rk.GetValue("i_backcolorAlt", unchecked((int)(0xfff0f8ff))));         // Color.AliceBlue
            button_selectcolor.ForeColor = Color.FromArgb((int)rk.GetValue("i_selectcolor", unchecked((int)(0xffffffff))));           // Color.White
            button_selectbackcolor.BackColor = Color.FromArgb((int)rk.GetValue("i_selectbackcolor", unchecked((int)(0xff3399ff))));   // Blue Green

            // ボタンの残りの色設定
            button_color.BackColor = button_backcolor.BackColor;
            button_backcolor.ForeColor = button_color.ForeColor;
            button_backcolorAlt.ForeColor = button_color.ForeColor;

            // 補色はあまり意味がない。
            //button_backcolor.ForeColor = Color.FromArgb((int)calc_complementary_color((uint)button_backcolor.BackColor.ToArgb()));
            //button_backcolorAlt.ForeColor = Color.FromArgb((int)calc_complementary_color((uint)button_backcolorAlt.BackColor.ToArgb()));

            // 選択の場合も同様
            button_selectcolor.BackColor = button_selectbackcolor.BackColor;
            button_selectbackcolor.ForeColor = button_selectcolor.ForeColor;
            //button_selectbackcolor.ForeColor = Color.FromArgb((int)calc_complementary_color((uint)button_selectbackcolor.BackColor.ToArgb())); 

        }

        // 32bitのalpha,RGB値から、補色を求める。なおalpha値はそのまま。
        private static uint calc_complementary_color(uint current_color)
        {
            uint complementary_color = 0;

            // alpha値、RGB値を取り出す。
            uint alpha = (current_color & 0xff000000);                       // 
            uint red = (current_color & 0x00ff0000) >> 16;
            uint green = (current_color & 0x0000ff00) >> 8;
            uint blue = (current_color & 0x000000ff);

            uint[] rgb = { red, green, blue };
            uint[] c_rgb = { 0, 0, 0 };

            uint min = 255;
            uint max = 0;
            uint maxmin = 0;
            int i = 0;

            // 最大、最少を求める
            for (i = 0; i < 3; i++)
            {
                if (rgb[i] > max)
                    max = rgb[i];

                if (rgb[i] < min)
                    min = rgb[i];
            }
            maxmin = max + min;

            // 最大、最少の合計から、現在値を引く
            for (i = 0; i < 3; i++)
            {
                c_rgb[i] = maxmin - rgb[i];
            }

            // 32bit値に組み立てる。
            complementary_color = alpha | c_rgb[0] << 16 | c_rgb[1] << 8 | c_rgb[2];

            MessageBox.Show("current color " + current_color.ToString("X8") + "\ncomplementary color " + complementary_color.ToString("X8"));
            return complementary_color;
        }

        private void setEnvList(string envString, int mode)
        {
            string viewPath = String.Empty;

            switch (mode)
            {
                case 1:
                    {
                        // 1: user env
                        viewPath = System.Environment.GetEnvironmentVariable(envString, System.EnvironmentVariableTarget.User);

                        if (viewPath == null)
                        {
                            viewPath = "未設定";
                        }
                        break;
                    }

                case 2:
                    {
                        // 2: system env
                        viewPath = System.Environment.GetEnvironmentVariable(envString);

                        if (viewPath == null)
                        {
                            viewPath = "未設定";
                        }
                        break;
                    }
                case 3:
                    {
                        // 3: system env x 2
                        viewPath = System.Environment.GetEnvironmentVariable(envString.Split(' ')[0])
                            + System.Environment.GetEnvironmentVariable(envString.Split(' ')[1]);
                        break;
                    }

                case 4:
                    {
                        // for curent running nodoka.exe
                        RegistryKey rk = Registry.CurrentUser.OpenSubKey("Software\\appletkan\\nodoka");
                        viewPath = (string)rk.GetValue("currentPath", "不明");
                        break;
                    }

                case 5:
                    {
                        // for install path
                        break;
                    }

            }
            this.envList.Rows.Add(envString, viewPath);
        }

        // 行ヘッダーに行番号を書くコールバックルーチン
        void putLineNumber(object sender, DataGridViewRowPostPaintEventArgs e)
        {

            // 行番号描画領域の設定
            Rectangle rect = new Rectangle(
              e.RowBounds.Location.X,
              e.RowBounds.Location.Y,
              envList.RowHeadersWidth - 4,
              e.RowBounds.Height);

            // 行番号の描画
            TextRenderer.DrawText(
              e.Graphics,
              (e.RowIndex + 1).ToString(),
              envList.RowHeadersDefaultCellStyle.Font,
              rect,
              envList.RowHeadersDefaultCellStyle.ForeColor,
              TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 環境変数NODOKAの設定

            Form fSetNODOKA = new FormSetNODOKA();
            if (fSetNODOKA.ShowDialog() == DialogResult.OK)
            {
                // 環境変数として保存
                string value = FormSetNODOKA.Global_Val.envString;
                this.envList[1, 0].Value = value;
                System.Environment.SetEnvironmentVariable("NODOKA", value, System.EnvironmentVariableTarget.User);
            }
        }

        private void combo_font_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }

        private void button_selectFont_Click(object sender, EventArgs e)
        {
            FontDialog fontDialog1 = new FontDialog();

            fontDialog1.Font = new Font(text_font.Text, Convert.ToInt32(text_fontsize.Text));
            fontDialog1.MaxSize = 72;
            fontDialog1.MinSize = 8;

            fontDialog1.FontMustExist = true;
            fontDialog1.ShowColor = false;
            fontDialog1.ShowEffects = false;
            fontDialog1.ShowHelp = false;
            fontDialog1.ShowApply = false;
            fontDialog1.ScriptsOnly = false;
            fontDialog1.FixedPitchOnly = false;
            fontDialog1.AllowScriptChange = false;
            fontDialog1.AllowSimulations = true;
            fontDialog1.AllowVectorFonts = false;
            fontDialog1.AllowVerticalFonts = false;

            // ダイアログを表示し、戻り値が [OK] の場合は選択したフォントを textBox1 に適用する
            if (fontDialog1.ShowDialog() == DialogResult.OK)
            {
                text_font.Text = fontDialog1.Font.Name.ToString();
                text_font.Font = new Font(fontDialog1.Font.Name.ToString(), 10, fontDialog1.Font.Style);
                text_fontsize.Text = Math.Round(fontDialog1.Font.Size, MidpointRounding.AwayFromZero).ToString();

                text_fontstyle.Text = "標準";
                String tmpFSname = fontDialog1.Font.Style.ToString();
                text_fontstyle_reg.Text = tmpFSname;

                if (tmpFSname.IndexOf("Bold") >= 0)
                {
                    text_fontstyle.Text = "太字";
                }
                if (tmpFSname.IndexOf("Italic") >= 0)
                {
                    text_fontstyle.Text = "斜体";
                }
                if (tmpFSname.IndexOf("Bold, Italic") >= 0)
                {
                    text_fontstyle.Text = "太字 斜体";
                }
            }

            fontDialog1.Dispose();
        }

        private void FormSetting_FormClosed(object sender, FormClosedEventArgs e)
        {
            // コントロールの状態を保存する。
            RegistryKey rk = Registry.CurrentUser.CreateSubKey("Software\\appletkan\\nodoka");
            int saveData;

            // 終了時に位置を覚える
            saveData = checkBox_position.Checked ? 1 : 0;
            rk.SetValue("b_position", saveData);

            //ウィンドウサイズを覚える
            saveData = checkBox_windowsize.Checked ? 1 : 0;
            rk.SetValue("b_windowsize", saveData);

            //カラムサイズを覚える
            saveData = checkBox_colum.Checked ? 1 : 0;
            rk.SetValue("b_column", saveData);

            //フォントサイズを覚える
            saveData = checkBox_fontsize.Checked ? 1 : 0;
            rk.SetValue("b_fontsize", saveData);

            //予約語の強調表示
            saveData = checkBox_bold.Checked ? 1 : 0;
            rk.SetValue("b_bold", saveData);

            //ファイル名を上に表示する
            saveData = checkBox_filename_caption.Checked ? 1 : 0;
            rk.SetValue("b_filename_caption", saveData);

            //フォント名、フォントサイズ、フォントスタイル
            rk.SetValue("s_font", text_font.Text);
            rk.SetValue("i_fontsize", Convert.ToInt32(text_fontsize.Text));
            rk.SetValue("s_fontstyle", text_fontstyle_reg.Text);

            //デフォルトカラー
            saveData = check_bcolor.Checked ? 1 : 0;
            rk.SetValue("b_color", saveData);

            //各色設定
            rk.SetValue("i_color", button_color.ForeColor.ToArgb());
            rk.SetValue("i_backcolor", button_color.BackColor.ToArgb());
            rk.SetValue("i_backcolorAlt", button_backcolorAlt.BackColor.ToArgb());
            rk.SetValue("i_selectcolor", button_selectcolor.ForeColor.ToArgb());
            rk.SetValue("i_selectbackcolor", button_selectcolor.BackColor.ToArgb());

            //終了時に文字コード指定を覚える
            rk.SetValue("b_selectencode", checkBox_selectencode.Checked ? 1 : 0);

        }

        private void button_selectcolor_Click(object sender, EventArgs e)
        {
            if (check_bcolor.Checked != true)
            {

                // 文字の色
                ColorDialog colorDialog1 = new ColorDialog();
                colorDialog1.Color = button_color.ForeColor;
                colorDialog1.AllowFullOpen = true;
                colorDialog1.FullOpen = false;
                colorDialog1.AnyColor = true;
                colorDialog1.SolidColorOnly = false;
                colorDialog1.CustomColors = new int[] { 0xfff8f0, 0xff9933 };
                colorDialog1.ShowHelp = false;

                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    button_color.ForeColor = colorDialog1.Color;
                    button_backcolor.ForeColor = button_color.ForeColor;
                    button_backcolorAlt.ForeColor = button_color.ForeColor;
                }

                colorDialog1.Dispose();
            }
        }

        private void button_backcolor_Click(object sender, EventArgs e)
        {
            if (check_bcolor.Checked != true)
            {
                // バックカラーの設定
                ColorDialog colorDialog1 = new ColorDialog();
                colorDialog1.Color = button_color.BackColor;
                colorDialog1.AllowFullOpen = true;
                colorDialog1.FullOpen = false;
                colorDialog1.AnyColor = true;
                colorDialog1.SolidColorOnly = false;
                colorDialog1.CustomColors = new int[] { 0xfff8f0, 0xff9933 };
                colorDialog1.ShowHelp = false;

                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    button_color.BackColor = colorDialog1.Color;
                    button_backcolor.BackColor = button_color.BackColor;
                }

                colorDialog1.Dispose();
            }
        }

        private void button_backcolorAlt_Click(object sender, EventArgs e)
        {
            if (check_bcolor.Checked != true)
            {
                // オルタネートバックカラー
                ColorDialog colorDialog1 = new ColorDialog();
                colorDialog1.Color = button_backcolorAlt.BackColor;
                colorDialog1.AllowFullOpen = true;
                colorDialog1.FullOpen = false;
                colorDialog1.AnyColor = true;
                colorDialog1.SolidColorOnly = false;
                colorDialog1.CustomColors = new int[] { 0xfff8f0, 0xff9933 };
                colorDialog1.ShowHelp = false;

                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    button_backcolorAlt.BackColor = colorDialog1.Color;
                }

                colorDialog1.Dispose();
            }
        }

        private void button_selectcolor_Click_1(object sender, EventArgs e)
        {
            if (check_bcolor.Checked != true)
            {

                // 選択時の文字色
                ColorDialog colorDialog1 = new ColorDialog();
                colorDialog1.Color = button_selectcolor.ForeColor;
                colorDialog1.AllowFullOpen = true;
                colorDialog1.FullOpen = false;
                colorDialog1.AnyColor = true;
                colorDialog1.SolidColorOnly = false;
                colorDialog1.CustomColors = new int[] { 0xfff8f0, 0xff9933 };
                colorDialog1.ShowHelp = false;

                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    button_selectcolor.ForeColor = colorDialog1.Color;
                    button_selectbackcolor.ForeColor = button_selectcolor.ForeColor;
                }

                colorDialog1.Dispose();
            }
        }

        private void button_selectbackcolor_Click(object sender, EventArgs e)
        {
            if (check_bcolor.Checked != true)
            {

                // 選択時の背景色
                ColorDialog colorDialog1 = new ColorDialog();
                colorDialog1.Color = button_selectcolor.BackColor;
                colorDialog1.AllowFullOpen = true;
                colorDialog1.FullOpen = false;
                colorDialog1.AnyColor = true;
                colorDialog1.SolidColorOnly = false;
                colorDialog1.CustomColors = new int[] { 0xfff8f0, 0xff9933 };
                colorDialog1.ShowHelp = false;

                if (colorDialog1.ShowDialog() == DialogResult.OK)
                {
                    button_selectcolor.BackColor = colorDialog1.Color;
                    button_selectbackcolor.BackColor = button_selectcolor.BackColor;
                }

                colorDialog1.Dispose();
            }
        }

        private void check_bcolor_CheckStateChanged(object sender, EventArgs e)
        {
            // 値を取得して、☑されたならばデフォルト値に戻す。
            // 色を変える 1ならデフォルト

            // ボタン自体の Enabledは 1でもFalseにしない。表示色が変わるから。
            if (check_bcolor.Checked)
            {
                //色の取得
                button_color.ForeColor = Color.FromArgb(unchecked((int)(0xff000000)));              // Color.Black
                button_backcolor.BackColor = Color.FromArgb(unchecked((int)(0xffffffff)));          // Color.White
                button_backcolorAlt.BackColor = Color.FromArgb(unchecked((int)(0xfff0f8ff)));       // Color.AliceBlue
                button_selectcolor.ForeColor = Color.FromArgb(unchecked((int)(0xffffffff)));        // Color.White
                button_selectbackcolor.BackColor = Color.FromArgb(unchecked((int)(0xff3399ff)));    // Blue Green

                // ボタンの残りの色設定
                button_color.BackColor = button_backcolor.BackColor;
                button_backcolor.ForeColor = button_color.ForeColor;
                button_backcolorAlt.ForeColor = button_color.ForeColor;
                button_selectcolor.BackColor = button_selectbackcolor.BackColor;
                button_selectbackcolor.ForeColor = button_selectcolor.ForeColor;

            }
        }

        private void envList_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            // セルがダブルクリックされたら、そのフォルダを開く
            int currentRow = -1;
            string folder_name = String.Empty;

            try
            {
                currentRow = envList.SelectedRows[0].Index;
                if (currentRow >= 0)
                {
                    folder_name = envList[1, currentRow].Value.ToString();
                    if (folder_name != "未設定" && folder_name != "不明" && folder_name != String.Empty)
                    {
                        System.Diagnostics.Process.Start(folder_name);
                    }
                }
            }

            catch
            {
                // フォルダが存在しない場合などはここにくる。
                MessageBox.Show("フォルダが存在しません。", "のどかGuiEdit", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }
        }

        private void button_open_Click(object sender, EventArgs e)
        {
            envList_CellContentDoubleClick(sender, null);
        }
    }
}
