using System;
using System.ComponentModel.Composition;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Windows.Forms;
using FooEditEngine;
using FooEditEngine.Windows;
using FooEditor;
using FooEditor.Plugin;
using SinnpetPlugin.Properties;

namespace SinnpetPlugin
{
    [Export(typeof(IPlugin))]
    class SnippetPlugin : IPlugin
    {
        Editor editor;

        public void Initalize(Editor e)
        {
            editor = e;

            ToolStripMenuItem item = (ToolStripMenuItem)e.RootMenuStrip.Items[1];
            item.DropDownItems.Add(new ToolStripSeparator());
            item.DropDownItems.Add(new ToolStripMenuItem(Resources.MenuName, null, SnippetDialogToolStripMenuItem_Click));

            e.ContextMenuStrip.Items.Add(new ToolStripSeparator());
            e.ContextMenuStrip.Items.Add(new ToolStripMenuItem(Resources.MenuName, null, SnippetDialogToolStripMenuItem_Click));
        }

        public void ClosedApp()
        {
            return;
        }

        public void ShowConfigForm()
        {
            return;
        }

        private void SnippetDialogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            EditForm active = this.editor.EditForm;
            if (active == null)
                return;
            SinppetDialog dlg = new SinppetDialog();
            dlg.ShowDialog();
            if (dlg.SelectedText != null)
            {
                FooTextBox TextBox = active.fooTextBox1;

                int lineNumber = TextBox.LayoutLines.GetLineNumberFromIndex(active.fooTextBox1.SelectionStart);
                string lineString = TextBox.LayoutLines[lineNumber];
                int tabNum = lineString.Count((c) => { return c == '\t'; });

                StringBuilder tabs = new StringBuilder();
                for (int i = 0; i < tabNum; i++)
                    tabs.Append("\t");
                string[] oldValues = new string[] { "${encode}", "\\n", "\\t", "\\i" };
                string[] newValues = new string[] { active.enc.WebName, System.Environment.NewLine, "\t", tabs.ToString() };

                TextBox.SelectedText = Util.Replace(dlg.SelectedText,oldValues, newValues);
                TextBox.Refresh();
            }
        }
    }
}
