/* This file is part of AHD Subtitles Maker Professional
   A program can create and edit subtitles

   Copyright © Ala I Hadid 2009 - 2012

   This program is free software: you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation, either version 3 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using AHD.SM.ASMP;
using AHD.SM.Forms;
using RavSoft;
using System.Reflection;
using System.Resources;
namespace AHD.SM.Controls
{
    public partial class SubtitleTextEditor : UserControl
    {
        public SubtitleTextEditor()
        {
            InitializeComponent();
            //fill up fonts
            for (int i = 0; i < FontFamily.Families.Length; i++)
            {
                ComboBox_font.Items.Add(FontFamily.Families[i].Name);
            }
        }

        string startText = "";
        SubtitleText text;
        bool Save = false;
        bool autoHideStrip = false;
        bool update = true;
        ResourceManager resources = new ResourceManager("AHD.SM.Controls.LanguageResources.Resource",
   Assembly.GetExecutingAssembly());

        /// <summary>
        /// Rised up when the user changed the text or color, fornt ... etc
        /// </summary>
        public event EventHandler SubtitleTextChanged;
        public event EventHandler StyleEditorVisibleChanged;
        public event EventHandler SubtitleTextLengthChanged;
        public event EventHandler SubtitleTextRightToLeftValueChanged;
        /// <summary>
        /// Get or set the subtitle text
        /// </summary>
        public SubtitleText SubtitleText
        {
            get { return text; }
            set
            {
                text = value;
                if (value != null)
                    RefreshText();
                else
                    richTextBox1.Text = "";
                startText = richTextBox1.Text;
                Save = false;
            }
        }
        /// <summary>
        /// Get if right to left
        /// </summary>
        public bool SubtitleTextRightToLeft
        { get { return toolStripButton_rtl.Checked; } }
        public bool ShowMoveButton
        {
            get { return toolStripButton2.Visible; }
            set { toolStripSeparator9.Visible = toolStripButton2.Visible = value; }
        }
        public void RefreshText()
        {
            richTextBox1.Clear();
            richTextBox1.SelectionStart = 0;
            richTextBox1.RightToLeft = toolStripButton_rtl.Checked ? System.Windows.Forms.RightToLeft.Yes :
                System.Windows.Forms.RightToLeft.No;
            if (text.TextLines.Count > 0)
            {
                foreach (SubtitleLine line in text.TextLines)
                {
                    foreach (SubtitleChar chr in line.Chars)
                    {
                        if (chr.Font != null)
                            richTextBox1.SelectionFont = chr.Font;
                        else
                            richTextBox1.SelectionFont = new Font("Tahoma", 8, FontStyle.Regular);

                        richTextBox1.SelectionBullet = true;
                        if (chr.Color != null)
                            richTextBox1.SelectionColor = chr.Color;
                        else
                            richTextBox1.SelectionColor = Color.White;
                        richTextBox1.SelectedText = chr.TheChar.ToString();
                        switch (line.Alignement)
                        {
                            case LineAlignement.Center: richTextBox1.SelectionAlignment = HorizontalAlignment.Center; break;
                            case LineAlignement.Left: richTextBox1.SelectionAlignment = HorizontalAlignment.Left; break;
                            case LineAlignement.Right: richTextBox1.SelectionAlignment = HorizontalAlignment.Right; break;
                        }
                        richTextBox1.SelectionBullet = false;
                    }
                    if (line != text.TextLines[text.TextLines.Count - 1])
                        richTextBox1.SelectedText = "\n";
                }
            }
            else
            {
                richTextBox1.SelectionAlignment = HorizontalAlignment.Center;
            }

            UpdateButtons();
        }
        /// <summary>
        /// Get the length of the text in the editor (not the subtitle text)
        /// </summary>
        public int TextLength
        {
            get
            {
                if (text == null)
                    return 0;
                else
                {
                    return richTextBox1.Text.Length;
                }
            }
        }
        /// <summary>
        /// Get or set value indecate wether to active auto style editor hide
        /// </summary>
        public bool AutoHideStyleEditor
        { get { return autoHideStrip; } set { autoHideStrip = value; } }
        /// <summary>
        /// Get or set a value indecate wether to show the toolstrip that edit font, color and position
        /// </summary>
        public bool ShowStyleEditor
        { get { return toolStrip1.Visible; } set { toolStrip1.Visible = value; } }
        public bool ShowStatusStrip
        { get { return statusStrip1.Visible; } set { statusStrip1.Visible = value; } }
        public bool ReadOnly
        { get { return richTextBox1.ReadOnly; } set { richTextBox1.ReadOnly = value; } }
        public void UpdateButtons()
        {
            update = false;
            if (richTextBox1.SelectionFont != null)
            {
                toolStripTextBox_fontSize.Text = richTextBox1.SelectionFont.Size.ToString();
                ComboBox_font.SelectedItem = richTextBox1.SelectionFont.Name;

                toolStripButton_bold.Checked = richTextBox1.SelectionFont.Bold;
                toolStripButton_italic.Checked = richTextBox1.SelectionFont.Italic;
                toolStripButton_underline.Checked = richTextBox1.SelectionFont.Underline;
                toolStripButton_strikeout.Checked = richTextBox1.SelectionFont.Strikeout;
            }
            switch (richTextBox1.SelectionAlignment)
            {
                case HorizontalAlignment.Left:
                    leftToolStripMenuItem.Checked = toolStripButton_leftAlign.Checked = true;
                    rightToolStripMenuItem.Checked = toolStripButton_rightAlign.Checked = false;
                    centerToolStripMenuItem.Checked = toolStripButton_centerAlign.Checked = false;
                    break;
                case HorizontalAlignment.Center:
                    leftToolStripMenuItem.Checked = toolStripButton_leftAlign.Checked = false;
                    rightToolStripMenuItem.Checked = toolStripButton_rightAlign.Checked = false;
                    centerToolStripMenuItem.Checked = toolStripButton_centerAlign.Checked = true;
                    break;
                case HorizontalAlignment.Right:
                    leftToolStripMenuItem.Checked = toolStripButton_leftAlign.Checked = false;
                    rightToolStripMenuItem.Checked = toolStripButton_rightAlign.Checked = true;
                    centerToolStripMenuItem.Checked = toolStripButton_centerAlign.Checked = false;
                    break;
            }
            if (text != null)
                toolStripButton_rtl.Checked = text.RighttoLeft;
            update = true;
        }
        public void UpdateSelectionFont()
        {
            if (ComboBox_font.SelectedIndex >= 0)
            {
                FontStyle style = FontStyle.Regular;
                if (!FontFamily.Families[ComboBox_font.SelectedIndex].IsStyleAvailable(FontStyle.Regular))
                    style ^= FontStyle.Regular;
                if (toolStripButton_bold.Checked)
                    style |= FontStyle.Bold;
                if (toolStripButton_italic.Checked)
                    style |= FontStyle.Italic;
                if (toolStripButton_underline.Checked)
                    style |= FontStyle.Underline;
                if (toolStripButton_strikeout.Checked)
                    style |= FontStyle.Strikeout;
                //create the font
                richTextBox1.SelectionFont = new Font(ComboBox_font.SelectedItem.ToString(), float.Parse(toolStripTextBox_fontSize.Text), style);
            }
        }
        public void SaveTextToSubtitle()
        {
            if (richTextBox1.ReadOnly)
                return;
            if (text == null)
                return;
            text.RighttoLeft = toolStripButton_rtl.Checked;
            text.TextLines.Clear();
            foreach (string ln in richTextBox1.Lines)
            {
                text.TextLines.Add(new SubtitleLine());
            }
            int currentLine = 0;
            int oldStart = richTextBox1.SelectionStart;
            string oldSelection = richTextBox1.SelectedText;
            richTextBox1.SelectionStart = 1;
            bool needToSetAlign = true;
            foreach (char chr in richTextBox1.Text.ToCharArray())
            {
                if (chr != '\n')
                {
                    if (needToSetAlign)
                    {
                        LineAlignement align = LineAlignement.Center;
                        switch (richTextBox1.SelectionAlignment)
                        {
                            case HorizontalAlignment.Left: align = LineAlignement.Left; break;
                            case HorizontalAlignment.Right: align = LineAlignement.Right; break;
                        }
                        text.TextLines[currentLine].Alignement = align;
                        needToSetAlign = false;
                    }
                    text.TextLines[currentLine].Chars.Add(new SubtitleChar(chr, richTextBox1.SelectionFont, richTextBox1.SelectionColor));
                }
                else
                {
                    currentLine++;
                    needToSetAlign = true;
                }
                richTextBox1.SelectionStart++;
            }
            richTextBox1.SelectionStart = oldStart + oldSelection.Length;
            richTextBox1.Select(oldStart, oldSelection.Length);
        }

        public void Copy()
        { richTextBox1.Copy(); }
        public void Cut()
        { richTextBox1.Cut(); }
        public void Paste()
        { richTextBox1.Paste(); }
        public void SelectAll()
        { richTextBox1.SelectAll(); }
        public void ChangeFont()
        {
            FontDialog dial = new FontDialog();
            dial.Font = richTextBox1.SelectionFont;
            if (dial.ShowDialog(this) == DialogResult.OK)
            {
                richTextBox1.SelectionFont = dial.Font;
                Save = true;
                UpdateButtons();
            }
        }
        public void ChangeColor()
        {
            ColorDialog dial = new ColorDialog();
            dial.Color = richTextBox1.SelectionColor;
            if (dial.ShowDialog(this) == DialogResult.OK)
            {
                richTextBox1.SelectionColor = dial.Color;
                Save = true;
            }
        }
        public void UpdateStatus()
        {
            int lineIndex = richTextBox1.GetLineFromCharIndex(richTextBox1.GetFirstCharIndexOfCurrentLine());
            toolStripStatusLabel1.Text = resources.GetString("Status_Line") + " " +
                (lineIndex + 1) + "/" + richTextBox1.Lines.Length + ", " +
                resources.GetString("Status_LineCharsCount") + "=" +
                ((richTextBox1.Lines.Length > lineIndex) ? richTextBox1.Lines[lineIndex].Length.ToString() : "0") + ", " +
               resources.GetString("Status_TotalCharsCount") + "=" + richTextBox1.Text.Length;
        }
        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (startText != "")
                if (richTextBox1.Text != startText)
                    Save = true;
            if (SubtitleTextLengthChanged != null)
                SubtitleTextLengthChanged(this, new EventArgs());

            UpdateStatus();
        }
        private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
            UpdateButtons();
        }
        private void richTextBox1_KeyDown(object sender, KeyEventArgs e)
        {
            UpdateButtons();
        }
        private void richTextBox1_MouseClick(object sender, MouseEventArgs e)
        {
            //if (pselectionStart != richTextBox1.SelectionStart) 
            UpdateButtons(); UpdateStatus();
            // pselectionStart = richTextBox1.SelectionStart;
        }
        private void ComboBox_font_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ComboBox_font.SelectedIndex < 0)
                return;
            //enable style buttons
            if (!FontFamily.Families[ComboBox_font.SelectedIndex].IsStyleAvailable(FontStyle.Bold))
            { toolStripButton_bold.Checked = toolStripButton_bold.Enabled = false; }
            if (!FontFamily.Families[ComboBox_font.SelectedIndex].IsStyleAvailable(FontStyle.Italic))
            { toolStripButton_italic.Checked = toolStripButton_italic.Enabled = false; }
            if (!FontFamily.Families[ComboBox_font.SelectedIndex].IsStyleAvailable(FontStyle.Strikeout))
            { toolStripButton_strikeout.Checked = toolStripButton_strikeout.Enabled = false; }
            if (!FontFamily.Families[ComboBox_font.SelectedIndex].IsStyleAvailable(FontStyle.Underline))
            { toolStripButton_underline.Checked = toolStripButton_underline.Enabled = false; }
            UpdateSelectionFont();
        }
        private void toolStripButton_bold_Click(object sender, EventArgs e)
        {
            UpdateSelectionFont(); Save = true;
        }
        private void toolStripButton_italic_Click(object sender, EventArgs e)
        {
            UpdateSelectionFont(); Save = true;
        }
        private void toolStripButton_underline_Click(object sender, EventArgs e)
        {
            UpdateSelectionFont(); Save = true;
        }
        private void toolStripButton_strikeout_Click(object sender, EventArgs e)
        {
            UpdateSelectionFont(); Save = true;
        }
        private void toolStripButton_leftAlign_Click(object sender, EventArgs e)
        {
            leftToolStripMenuItem.Checked = toolStripButton_leftAlign.Checked = true;
            rightToolStripMenuItem.Checked = toolStripButton_rightAlign.Checked = false;
            centerToolStripMenuItem.Checked = toolStripButton_centerAlign.Checked = false;
            richTextBox1.SelectionAlignment = HorizontalAlignment.Left; Save = true;
        }
        private void toolStripButton_centerAlign_Click(object sender, EventArgs e)
        {
            leftToolStripMenuItem.Checked = toolStripButton_leftAlign.Checked = false;
            rightToolStripMenuItem.Checked = toolStripButton_rightAlign.Checked = false;
            centerToolStripMenuItem.Checked = toolStripButton_centerAlign.Checked = true;
            richTextBox1.SelectionAlignment = HorizontalAlignment.Center; Save = true;
        }
        private void toolStripButton_rightAlign_Click(object sender, EventArgs e)
        {
            leftToolStripMenuItem.Checked = toolStripButton_leftAlign.Checked = false;
            rightToolStripMenuItem.Checked = toolStripButton_rightAlign.Checked = true;
            centerToolStripMenuItem.Checked = toolStripButton_centerAlign.Checked = false;
            richTextBox1.SelectionAlignment = HorizontalAlignment.Right; Save = true;
        }
        private void toolStripTextBox_fontSize_TextChanged(object sender, EventArgs e)
        {
            if (!update)
                return;
            float size = 0;
            if (float.TryParse(toolStripTextBox_fontSize.Text, out size))
            {
                UpdateSelectionFont(); Save = true;
            }
            else
            {
                toolStripTextBox_fontSize.Text = richTextBox1.SelectionFont.Size.ToString();
            }
        }
        private void toolStripButton9_Click(object sender, EventArgs e)
        {
            ChangeColor();
        }
        private void toolStripButton8_Click(object sender, EventArgs e)
        {
            ChangeFont();
        }
        private void ComboBox_font_DropDownClosed(object sender, EventArgs e)
        {
            richTextBox1.Select();
            Save = true;
        }
        //Save methods
        private void richTextBox1_Validated(object sender, EventArgs e)
        {
            if (Save)
            {
                SaveTextToSubtitle();
                if (SubtitleTextChanged != null)
                    SubtitleTextChanged(this, new EventArgs());
            }
            Save = false;
        }
        private void richTextBox1_Leave(object sender, EventArgs e)
        {
            if (Save)
            {
                SaveTextToSubtitle();
                if (SubtitleTextChanged != null)
                    SubtitleTextChanged(this, new EventArgs());
            }
            Save = false;

            if (autoHideStrip)
                toolStrip1.Visible = false;
        }
        private void richTextBox1_Enter(object sender, EventArgs e)
        {
            if (autoHideStrip)
                toolStrip1.Visible = true;
        }
        private void copyToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Copy();
        }
        private void cutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Cut();
        }
        private void pasteToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Paste();
        }
        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SelectAll();
        }
        private void toolStrip1_VisibleChanged(object sender, EventArgs e)
        {
            if (StyleEditorVisibleChanged != null)
                StyleEditorVisibleChanged(sender, e);
        }
        //google translate
        private void toolStripButton1_Click(object sender, EventArgs e)
        {
            if (richTextBox1.SelectedText.Length == 0)
                richTextBox1.SelectAll();
            Frm_TranslateLanguageFromTo frm = new Frm_TranslateLanguageFromTo();
            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                Translator translator = new Translator();
                translator.TargetLanguage = frm.LanguageTo;
                translator.SourceLanguage = frm.LanguageFrom;

                string[] text = richTextBox1.SelectedText.Split(new char[] { '\n' });
                string translation = "";
                foreach (string line in text)
                {
                    translator.SourceText = line.ToString();
                    translator.Translate();
                    translation += translator.Translation + "\n";
                }
                translation = translation.Substring(0, translation.Length - 1);

                richTextBox1.Cut();
                richTextBox1.SelectedText = translation;
            }
        }
        //change location
        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            Frm_SubtitlePosition frm = new Frm_SubtitlePosition(this.text);
            frm.Location = new Point(Cursor.Position.X, Cursor.Position.Y - frm.Size.Height);
            if (frm.ShowDialog(this) == DialogResult.OK)
            {
                if (SubtitleTextChanged != null)
                    SubtitleTextChanged(this, new EventArgs());
            }
        }

        private void toolStripButton3_Click(object sender, EventArgs e)
        {
            text.RighttoLeft = !text.RighttoLeft;
            toolStripButton_rtl.Checked = text.RighttoLeft;
            richTextBox1.RightToLeft = toolStripButton_rtl.Checked ? System.Windows.Forms.RightToLeft.Yes :
                System.Windows.Forms.RightToLeft.No;
            if (SubtitleTextRightToLeftValueChanged != null)
                SubtitleTextRightToLeftValueChanged(this, null);
        }

        public override Color BackColor
        {
            get
            {
                return base.BackColor;
            }
            set
            {
                richTextBox1.BackColor = base.BackColor = value;
            }
        }

        /*private void toolStripButton3_Click(object sender, EventArgs e)
        {
            SaveFileDialog sav = new SaveFileDialog();
            sav.Filter = "text|*.txt";
            if (sav.ShowDialog(this) == DialogResult.OK)
            {
                richTextBox1.SaveFile(sav.FileName);
            }
        }*/
    }
}
