using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using WeifenLuo.WinFormsUI.Docking;
using MySQL.Grt;
using MySQL.Grt.Db;
using MySQL.Utilities;
using MySQL.GUI.Workbench;

namespace MySQL.GUI.Workbench.Plugins
{
  public partial class DbMysqlSchemaEditor : ObjectEditorPlugin
  {
    #region Member Variables

    private MySQLSchemaEditorBE schemaEditorBE { get { return editorBE as MySQLSchemaEditorBE; } } 
    protected string oldName;
    protected bool settingOptions = false;

    #endregion

    #region Constructors

    protected DbMysqlSchemaEditor()
    {
      InitializeComponent();
    }

    public DbMysqlSchemaEditor(GrtManager GrtManager, GrtValue GrtObject)
      : base(new MySQLSchemaEditorBE(GrtManager, GrtObject))
    {
      InitializeComponent();
      InitializingControls = true;
      try
      {
        CallRefreshFormData();
      }
      finally
      {
        InitializingControls = false;
      }

      schemaEditorBE.add_refresh_ui_handler(RefreshFormDataInvoke);
    }

    #endregion

    #region IWorkbenchDocument implementation

    public override UIForm BackendClass
    {
      get { return schemaEditorBE; }
    }

    #endregion

    #region Form implemenation

    protected override void RefreshFormData()
    {
      if (settingOptions)
        return;

      try
      {
        nameTextBox.InitializingControl = true;
        oldName = schemaEditorBE.get_name();
        nameTextBox.Text = oldName;
      }
      finally
      {
        nameTextBox.InitializingControl = false;
      }

      System.Collections.Generic.List<String> collations_list = schemaEditorBE.get_charset_collation_list();

      optCollation.Items.Clear();
      optCollation.Items.Add("Server Default");

      foreach (String coll in collations_list)
        optCollation.Items.Add(coll);

      int idx = 0;
      String cscoll = schemaEditorBE.get_schema_option_by_name("CHARACTER SET")
                    + " - " + schemaEditorBE.get_schema_option_by_name("COLLATE");

      // beware: this line changes cs value in backend
      optCollation.SelectedIndex = 0;

      foreach (String next_cscoll in optCollation.Items)
      {
        if (next_cscoll == cscoll)
        {
          optCollation.SelectedIndex = idx;
          break;
        }
        idx++;
      }

      TabText = nameTextBox.Text;

      optComments.Text = schemaEditorBE.get_comment();
    }

    private void nameTextBox_TextChanged(object sender, EventArgs e)
    {
      if (!InitializingControls && !nameTextBox.Text.Equals(schemaEditorBE.get_name()))
        schemaEditorBE.set_name(nameTextBox.Text);

      TabText = nameTextBox.Text;
    }

    private void optCollation_SelectedIndexChanged(object sender, EventArgs e)
    {
      setSchemaOpt();
    }

    private void optComments_TextChanged(object sender, EventArgs e)
    {
      setSchemaOpt();
    }

    private void setSchemaOpt()
    {
      // When a UI value changes, update the schema options
      if (InitializingControls)
        return;

      settingOptions = true;
      try
      {
        // set charset/collation
        if (optCollation.SelectedIndex == 0)
        {
          schemaEditorBE.set_schema_option_by_name("CHARACTER SET", "");
          schemaEditorBE.set_schema_option_by_name("COLLATE", "");
        }
        else
        {
          int cs_sep = optCollation.Text.IndexOf('-');
          if (cs_sep != -1)
          {
            schemaEditorBE.set_schema_option_by_name("CHARACTER SET", optCollation.Text.Substring(0, cs_sep - 1));
            schemaEditorBE.set_schema_option_by_name("COLLATE", optCollation.Text.Substring(cs_sep + 2));
          }
        }

        if (!optComments.Text.Equals(schemaEditorBE.get_comment()))
          schemaEditorBE.set_comment(optComments.Text);

      }
      finally
      {
        settingOptions = false;
      }
    }

    private void nameTextBox_DocAction(object sender, EventArgs eventArgs)
    {
      schemaEditorBE.refactor_catalog_upon_schema_rename(oldName, nameTextBox.Text);

      // reset oldName for next refactoring
      oldName = nameTextBox.Text;
    }

    private void nameTextBox_Validating(object sender, CancelEventArgs e)
    {
      if (oldName == nameTextBox.Text)
        return;

      DialogResult result;
      result = MessageBox.Show("Rename all schema occurences?", "Schema name changed",
        MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
      if (result == DialogResult.Yes)
      {
        nameTextBox.HideDocActionPictureBox();
        schemaEditorBE.refactor_catalog_upon_schema_rename(oldName, nameTextBox.Text);
        // reset oldName for next refactoring
        oldName = nameTextBox.Text;
      }
      else if (result == DialogResult.Cancel)
        e.Cancel = true;
      else if (result == DialogResult.No)
        nameTextBox.HideDocActionPictureBox();
    }

    #endregion

  }
}