using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Aga.Controls.Tree;


namespace MySQL.Grt.Db
{
  public partial class DbSqlEditor : MySQL.GUI.Workbench.Plugins.DockablePlugin
  {
    private Db_sql_editor dbSqlEditorBE;
    private List<TabPage> resPages = new List<TabPage>();
    private Sql.SqlEditor sqlEditor;

    public DbSqlEditor(GrtManager grtManager, GrtValue grtObject)
    {
      dbSqlEditorBE = new Db_sql_editor(grtManager);

      InitializeComponent();

      Text = "SQL Editor";
      TabText = Text;

      sqlEditor = new Sql.SqlEditor(grtManager);
      sqlEditor.BE = dbSqlEditorBE.sql_editor();
      sqlEditor.Parent = splitContainer.Panel1;
      sqlEditor.Text = "select * from information_schema.engines"; //!
      sqlEditor.Selection.Start = sqlEditor.Text.Length;
      sqlEditor.Selection.End = sqlEditor.Text.Length;

      ActiveControl = sqlEditor;
    }

    private void execSql_Click(object sender, EventArgs e)
    {
      foreach (TabPage page in resPages)
        queryTabs.TabPages.Remove(page);
      resPages.Clear();

      try
      {
        dbSqlEditorBE.exec_sql(sqlEditor.Text);


        for (int n = 0, rsCount = dbSqlEditorBE.recordset_count(); n < rsCount; ++n)
        {
          TabPage page = new TabPage(string.Format("Result {0}", n + 1));
          TreeViewAdv view = new TreeViewAdv();
          view.SelectedNode = null;
          view.LoadOnDemand = true;
          view.ShowPlusMinus = false;
          view.UseColumns = true;
          view.ShowLines = true;
          view.Dock = DockStyle.Fill;
          view.Parent = page;
          queryTabs.TabPages.Insert(n, page);
          resPages.Add(page);

          RecordsetModel model = new RecordsetModel(view, dbSqlEditorBE.recordset(n));

          view.Model = model;
          view.Refresh();

          historyTB.Text += sqlEditor.Text + System.Console.Out.NewLine;
        }

        //! setup tpMessages (no. of rows returned)

        queryTabs.SelectedTab = queryTabs.TabPages[0];
      }
      catch (Exception)
      {
        //! setup tpMessages (error message)
      }
    }
  }
}
