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;

namespace Mix.Tool.ModelEditor
{
    public partial class NewProjectForm : Form
    {
        const int CB_OUTPUT_FORMAT_ACTOR = 0;
        const int CB_OUTPUT_FORMAT_TERRAIN = 1;
        const int CB_OUTPUT_MTM_30 = 0;
        const int CB_OUTPUT_MTM_60 = 1;

        const int CB_OPTION_DEFAULT = 0;
        const int CB_OPTION_FBX_MAYA = 1;
        const int CB_OPTION_FBX_3DSMAX = 2;

        private Project.Manager project = null;

        public NewProjectForm(Project.Manager _project)
        {
            InitializeComponent();

            this.project = _project;

            this.cbSmooting.Checked = this.project.Config.Smooting.Enabled;
            this.nudSmootingAngle.Value = Convert.ToDecimal(this.project.Config.Smooting.Angle);

            this.cbOutputFormat.Items.Add(Properties.Resources.OUTPUT_MODEL_FMT_ACTOR);
            this.cbOutputFormat.Items.Add(Properties.Resources.OUTPUT_MODEL_FMT_TERRAIN);
            this.cbOutputFormat.SelectedIndex = CB_OUTPUT_FORMAT_ACTOR;

            this.cbOption.Items.Add(Properties.Resources.JP_DEFAULT);
            this.cbOption.Items.Add(Properties.Resources.IMPORT_OPT_FBX_Maya);
            this.cbOption.Items.Add(Properties.Resources.IMPORT_OPT_FBX_3DSMax);
            this.cbOption.SelectedIndex = 0;

            this.cbOutputMotTimeMode.Items.Add(Properties.Resources.OUTPUT_MOT_TM_30);
            this.cbOutputMotTimeMode.Items.Add(Properties.Resources.OUTPUT_MOT_TM_60);
            this.cbOutputMotTimeMode.SelectedIndex = CB_OUTPUT_MTM_60;

            this.UpdateControlesEnabled();
        }

        private void NewProjectForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.DialogResult == DialogResult.No)
            {
                e.Cancel = true;
            }
        }

        private void tbBasicRootDir_TextChanged(object sender, EventArgs e)
        {
            this.UpdateControlesEnabled();
        }

        private void btBasicRootDir_Click(object sender, EventArgs e)
        {
            using (Mix.Tool.DirectoryBrowseDialog dlg = new DirectoryBrowseDialog())
            {
                dlg.Root = DirectoryBrowseDialog.RootType.Specify;
                dlg.RootDirectoryName = "";
                dlg.DirectoryName = this.tbBasicRootDir.Text;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    this.tbBasicRootDir.Text = dlg.DirectoryName;
                }
            }
        }

        private void tbBasicTemplateDesc_TextChanged(object sender, EventArgs e)
        {
            this.UpdateControlesEnabled();
        }

        private void btBasicTemplateOpen_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                if (this.project.Template.FilePath.Length > 0)
                {
                    try
                    {
                        dlg.InitialDirectory = System.IO.Path.GetDirectoryName(this.project.Template.FilePath);
                    }
                    catch
                    {
                        dlg.InitialDirectory = System.IO.Path.GetPathRoot(this.project.Template.FilePath);
                    }

                    dlg.FileName = System.IO.Path.GetFileName(this.project.Template.FilePath);
                }
                else
                {
                    dlg.InitialDirectory = "";
                    dlg.FileName = "";
                }

                dlg.Filter = Properties.Resources.FILE_FILTER_PTM;
                dlg.FilterIndex = 1;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    this.project.Template.FilePath = dlg.FileName;

                    try
                    {
                        this.project.Template.Load();
                        this.tbBasicTemplateDesc.Text = this.project.Template.Desc;
                    }
                    catch (System.Exception excep)
                    {
                        this.ShowErrorBox(Properties.Resources.PROJECT_TEMPLATE_OPEN_ERROR + excep.Message);
                    }
                }
            }
        }

        private void btBasicTemplateEdit_Click(object sender, EventArgs e)
        {
            using (ProjectTemplateForm form = new ProjectTemplateForm(this.tbBasicRootDir.Text, this.project.Template))
            {
                if (form.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        this.project.Template.Save();
                        this.tbBasicTemplateDesc.Text = this.project.Template.Desc;
                    }
                    catch (System.Exception excep)
                    {
                        this.ShowErrorBox(Properties.Resources.PROJECT_TEMPLATE_SAVE_ERROR + excep.Message);
                    }
                }
            }
        }

        private void tbInputFile_TextChanged(object sender, EventArgs e)
        {
            this.UpdateControlesEnabled();
        }

        private void btInputFile_Click(object sender, EventArgs e)
        {
            using (OpenFileDialog dlg = new OpenFileDialog())
            {
                dlg.Filter = Properties.Resources.FILE_FILTER_INPUTMODEL;
                dlg.FilterIndex = 1;

                if (this.tbInputFile.Text.Length > 0)
                {
                    try
                    {
                        dlg.InitialDirectory = System.IO.Path.GetDirectoryName(this.tbInputFile.Text);
                    }
                    catch
                    {
                        dlg.InitialDirectory = System.IO.Path.GetPathRoot(this.tbInputFile.Text);
                    }

                    dlg.FileName = System.IO.Path.GetFileName(this.tbInputFile.Text);
                }
                else
                {
                    dlg.InitialDirectory = "";
                    dlg.FileName = "";
                }

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    string preDirName = "";

                    if (this.tbInputFile.Text.Length > 0)
                    {
                        try { preDirName = System.IO.Path.GetDirectoryName(this.tbInputFile.Text); } catch { }
                    }

                    try
                    {
                        string dirName = System.IO.Path.GetDirectoryName(dlg.FileName);

                        if ((this.tbProjectDirPath.Text.Length == 0) ||
                            (this.tbProjectDirPath.Text.Equals(preDirName) == true))
                        {
                            this.tbProjectDirPath.Text = dirName;
                        }
                    } catch { }

                    this.tbInputFile.Text = dlg.FileName;
                }
            }
        }

        private void cbOutputFormat_SelectedIndexChanged(object sender, EventArgs e)
        {
            string rootDirPath;
            string fileName;
            string fileExt;

            if (this.tbOutputFile.Text.Length > 0)
            {
                try
                {
                    rootDirPath = System.IO.Path.GetDirectoryName(this.tbOutputFile.Text);
                }
                catch
                {
                    try
                    {
                        rootDirPath = System.IO.Path.GetPathRoot(this.tbOutputFile.Text);
                    }
                    catch
                    {
                        rootDirPath = "";
                    }
                }

                try
                {
                    fileName = System.IO.Path.GetFileNameWithoutExtension(this.tbOutputFile.Text);
                }
                catch
                {
                    fileName = "";
                }

                switch (this.cbOutputFormat.SelectedIndex)
                {
                    case CB_OUTPUT_FORMAT_ACTOR:
                        fileExt = Properties.Resources.FILE_EXT_MAM;
                        break;
                    case CB_OUTPUT_FORMAT_TERRAIN:
                        fileExt = Properties.Resources.FILE_EXT_MTM;
                        break;
                    default:
                        fileExt = "";
                        break;
                }

                try
                {
                    if (fileExt.Length > 0)
                    {
                        this.tbOutputFile.Text = System.IO.Path.Combine(rootDirPath, fileName) + fileExt;
                    }
                    else
                    {
                        throw new ArgumentException();
                    }
                }
                catch
                {
                    this.tbOutputFile.Text = "";
                }
            }

            this.UpdateControlesEnabled();
        }

        private void tbOutputFile_TextChanged(object sender, EventArgs e)
        {
            this.UpdateControlesEnabled();
        }

        private void btOutputFile_Click(object sender, EventArgs e)
        {
            using (SaveFileDialog dlg = new SaveFileDialog())
            {
                switch (this.cbOutputFormat.SelectedIndex)
                {
                    case CB_OUTPUT_FORMAT_ACTOR:
                        dlg.Filter = Properties.Resources.FILE_FILTER_MAM;
                        break;
                    case CB_OUTPUT_FORMAT_TERRAIN:
                        dlg.Filter = Properties.Resources.FILE_FILTER_MTM;
                        break;
                }

                dlg.FilterIndex = 1;

                if (this.tbOutputFile.Text.Length > 0)
                {
                    try
                    {
                        dlg.InitialDirectory = System.IO.Path.GetDirectoryName(this.tbOutputFile.Text);
                    }
                    catch
                    {
                        dlg.InitialDirectory = System.IO.Path.GetPathRoot(this.tbOutputFile.Text);
                    }

                    dlg.FileName = System.IO.Path.GetFileName(this.tbOutputFile.Text);
                }
                else
                {
                    dlg.InitialDirectory = "";
                    dlg.FileName = "";
                }

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    this.tbOutputFile.Text = dlg.FileName;
                }

                this.UpdateControlesEnabled();
            }
        }

        private void btOutputFileClear_Click(object sender, EventArgs e)
        {
            this.tbOutputFile.Text = "";
        }

        private void tbProjectName_TextChanged(object sender, EventArgs e)
        {
            this.UpdateControlesEnabled();
        }

        private void tbProjectDirPath_TextChanged(object sender, EventArgs e)
        {
            this.UpdateControlesEnabled();
        }

        private void btProjectDirPath_Click(object sender, EventArgs e)
        {
            using (Mix.Tool.DirectoryBrowseDialog dlg = new DirectoryBrowseDialog())
            {
                dlg.Root = DirectoryBrowseDialog.RootType.Specify;
                dlg.RootDirectoryName = "";
                dlg.DirectoryName = this.tbProjectDirPath.Text;

                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    this.tbProjectDirPath.Text = dlg.DirectoryName;
                }
            }
        }

        private void btOK_Click(object sender, EventArgs e)
        {
            ////////////////////////////////////////////////////////////////////////////////////////////////////
            // 基本
            ////////////////////////////////////////////////////////////////////////////////////////////////////

            //ルートディレクトリパス
            this.project.RootDirectoryPath = this.tbBasicRootDir.Text;

            //テンプレートファイルパスは設定済み
            ;

            ////////////////////////////////////////////////////////////////////////////////////////////////////
            // リソース
            ////////////////////////////////////////////////////////////////////////////////////////////////////

            Mix.Tool.Math.Vector rotation = new Mix.Tool.Math.Vector();
            Mix.Tool.Math.Vector translation = new Mix.Tool.Math.Vector();

            //入力ファイル
            this.project.Config.InputFilePath = this.tbInputFile.Text;

            //出力ファイル
            this.project.Config.OutputFilePath = this.tbOutputFile.Text;

            //オプション
            switch (this.cbOption.SelectedIndex)
            {
                case CB_OPTION_DEFAULT:
                    this.project.Config.Option = Mix.Tool.Graphics.ModelImportOption.Default;
                    break;
                case CB_OPTION_FBX_MAYA:
                    this.project.Config.Option = Mix.Tool.Graphics.ModelImportOption.FBX_Maya;
                    break;
                case CB_OPTION_FBX_3DSMAX:
                    this.project.Config.Option = Mix.Tool.Graphics.ModelImportOption.FBX_3DStudioMax;
                    break;
                default:
                    throw new System.Exception();
            }

            //スケール
            this.project.Config.Transform.Scaling = (float)Convert.ToDouble(this.nudS.Value);

            //回転
            rotation.X = (float)Convert.ToDouble(this.nudRX.Value);
            rotation.Y = (float)Convert.ToDouble(this.nudRY.Value);
            rotation.Z = (float)Convert.ToDouble(this.nudRZ.Value);
            this.project.Config.Transform.Rotation = rotation;

            //移動
            translation.X = (float)Convert.ToDouble(this.nudTX.Value);
            translation.Y = (float)Convert.ToDouble(this.nudTY.Value);
            translation.Z = (float)Convert.ToDouble(this.nudTZ.Value);
            this.project.Config.Transform.Translation = translation;

            //スムーージング
            this.project.Config.Smooting.Enabled = this.cbSmooting.Checked;
            this.project.Config.Smooting.Angle = (float)Convert.ToDouble(this.nudSmootingAngle.Value);

            //フォーマット
            switch( this.cbOutputFormat.SelectedIndex )
            {
                case CB_OUTPUT_FORMAT_ACTOR:
                    this.project.Config.Format = Project.ModelFormats.Actor;
                    break;
                case CB_OUTPUT_FORMAT_TERRAIN:
                    this.project.Config.Format = Project.ModelFormats.Terrain;
                    break;
                default:
                    throw new System.Exception();
            }

            //タイムモード(アクターモデル)
            switch (this.cbOutputMotTimeMode.SelectedIndex)
            {
                case CB_OUTPUT_MTM_30:
                    this.project.Config.OM_TimeMode = Mix.Tool.Graphics.ObjectModel.TimeModes.Frames30;
                    break;
                case CB_OUTPUT_MTM_60:
                    this.project.Config.OM_TimeMode = Mix.Tool.Graphics.ObjectModel.TimeModes.Frames60;
                    break;
                default:
                    throw new System.Exception();
            }

            //セルサイズ(マップモデル)
            this.project.Config.MM_CellSize = new Mix.Tool.Math.Vector((float)this.nudOutputCellSizeX.Value,
                (float)this.nudOutputCellSizeY.Value,
                (float)this.nudOutputCellSizeZ.Value);

            ////////////////////////////////////////////////////////////////////////////////////////////////////
            // プロジェクト
            ////////////////////////////////////////////////////////////////////////////////////////////////////

            //名前
            this.project.Name = this.tbProjectName.Text;

            //ディレクトリパス
            this.project.DirectoryPath = this.tbProjectDirPath.Text;

            //既存のプロジェクトの上書きチェック
            if (System.IO.File.Exists(this.project.FilePath) == true)
            {
                if (Mix.Tool.MessageDialog.ShowYN(string.Format(Properties.Resources.WARNING_PRJ_REWRITE, this.project.FilePath),
                    Properties.Resources.TITLE,
                    MessageDialogIcon.Warning) == DialogResult.No)
                {
                    //No にしてフォームを閉じる際にチェックさせる
                    this.DialogResult = DialogResult.No;
                }
            }
        }

        private void NewProjectForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
            {
                this.DialogResult = DialogResult.Cancel;
                this.Close();
            }
        }

        private void UpdateControlesEnabled()
        {
            bool basicEnabled = false;
            bool modelEnabled = false;
            bool projectEnabled = false;

            ////////////////////////////////////////////////////////////////////////////////////////////////////
            // 全般
            ////////////////////////////////////////////////////////////////////////////////////////////////////

            if (this.tbBasicRootDir.Text.Length > 0)
            {
                this.panelTemplate.Enabled = true;

                if (this.tbBasicTemplateDesc.Text.Length > 0)
                {
                    basicEnabled = true;
                }
            }
            else
            {
                this.panelTemplate.Enabled = false;
            }

            ////////////////////////////////////////////////////////////////////////////////////////////////////
            // モデル
            ////////////////////////////////////////////////////////////////////////////////////////////////////

            modelEnabled = (this.tbInputFile.Text.Length > 0);

            switch (this.cbOutputFormat.SelectedIndex)
            {
                case CB_OUTPUT_FORMAT_ACTOR:
                    this.panelOutputCellSize.Enabled = false;
                    this.panelOutputMotTimeMode.Enabled = true;
                    break;
                case CB_OUTPUT_FORMAT_TERRAIN:
                    this.panelOutputCellSize.Enabled = true;
                    this.panelOutputMotTimeMode.Enabled = false;
                    break;
            }

            ////////////////////////////////////////////////////////////////////////////////////////////////////
            // プロジェクト
            ////////////////////////////////////////////////////////////////////////////////////////////////////

            if ((this.tbProjectName.Text.Length > 0) &&
                (this.tbProjectDirPath.Text.Length > 0))
            {
                projectEnabled = true;
            }
            else
            {
                projectEnabled = false;
            }

            ////////////////////////////////////////////////////////////////////////////////////////////////////
            // OKボタン
            ////////////////////////////////////////////////////////////////////////////////////////////////////

            if ((basicEnabled == true) &&
                (modelEnabled == true) &&
                (projectEnabled == true))
            {
                this.btOK.Enabled = true;
            }
            else
            {
                this.btOK.Enabled = false;
            }
        }

        private void ShowErrorBox(string mes)
        {
            Mix.Tool.MessageDialog.Show(mes, Properties.Resources.TITLE, MessageDialogButtons.OK, MessageDialogIcon.Error);
        }
    }
}
