/* 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.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Resources;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;
using AHD.SM.ASMP;
using AHD.Forms;

namespace AHD.MKV
{
    public partial class Frm_VobSubtitlesToASMPSubtitles : Form
    {
        public Frm_VobSubtitlesToASMPSubtitles(List<VobSubMergedPack> mergedVobSubPacks, List<Color> palette)
        {
            InitializeComponent();
            this.palette = palette;
            foreach (VobSubMergedPack pack in mergedVobSubPacks)
            {
                ListViewItem_VobPack item = new ListViewItem_VobPack();
                item.VobSubMergedPack = pack;
                listView1.Items.Add(item);
            }
            comboBox1.SelectedIndex = 0;
            numericUpDown1.Maximum = mergedVobSubPacks.Count - 1;
        }
        List<Color> palette;
        SubtitlesTrack track;
        ResourceManager resources = new ResourceManager("AHD.MKV.LanguageResources.Resource",
      Assembly.GetExecutingAssembly());

        public SubtitlesTrack SubtitlesTrackGenerated
        { get { return track; } }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count != 1)
            {
                pictureBox1.Image = null;
                return;
            }
            ListViewItem_VobPack item = (ListViewItem_VobPack)listView1.SelectedItems[0];
            if (!checkBox_useCustomColors.Checked)
                pictureBox1.Image = item.VobSubMergedPack.VobSubPicture.GetBitmap(palette, Color.Transparent, Color.Black, Color.White, Color.Black);
            else
                pictureBox1.Image = item.VobSubMergedPack.VobSubPicture.GetBitmap(null, Color.Transparent, button_Pattern.BackColor,
                    button_Emphasis1.BackColor, button_Emphasis2.BackColor);

            richTextBox1.Text = item.GetText();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            //generate subtitles track
            track = new SubtitlesTrack();
            foreach (ListViewItem_VobPack item in listView1.Items)
            {
                Subtitle sub = new Subtitle(TimeFormatConvertor.From_TimeSpan_Milli(item.VobSubMergedPack.StartTime.ToString()),
                   TimeFormatConvertor.From_TimeSpan_Milli(item.VobSubMergedPack.EndTime.ToString()),
                   SubtitleText.FromString(item.GetText()));
                track.Subtitles.Add(sub);
            }
            //ok !
            this.DialogResult = System.Windows.Forms.DialogResult.OK;
            this.Close();
        }

        private void richTextBox1_TextChanged(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count == 1)
            {
                ((ListViewItem_VobPack)listView1.SelectedItems[0]).SetText(richTextBox1.Text);
            }
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            pictureBox1.SizeMode = checkBox1.Checked ? PictureBoxSizeMode.StretchImage : PictureBoxSizeMode.Normal;
        }

        private void button_Pattern_Click(object sender, EventArgs e)
        {
            ColorDialog dial = new ColorDialog();
            dial.Color = button_Pattern.BackColor;
            if (dial.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                button_Pattern.BackColor = dial.Color;
                listView1_SelectedIndexChanged(sender, e);
            }
        }

        private void button_Emphasis1_Click(object sender, EventArgs e)
        {
            ColorDialog dial = new ColorDialog();
            dial.Color = button_Emphasis1.BackColor;
            if (dial.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                button_Emphasis1.BackColor = dial.Color;
                listView1_SelectedIndexChanged(sender, e);
            }
        }

        private void button_Emphasis2_Click(object sender, EventArgs e)
        {
            ColorDialog dial = new ColorDialog();
            dial.Color = button_Emphasis2.BackColor;
            if (dial.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                button_Emphasis2.BackColor = dial.Color;
                listView1_SelectedIndexChanged(sender, e);
            }
        }

        private void checkBox_useCustomColors_CheckedChanged(object sender, EventArgs e)
        {
            listView1_SelectedIndexChanged(sender, e);
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            button_Pattern.BackColor = Color.Transparent;
            listView1_SelectedIndexChanged(sender, e);
        }

        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            button_Emphasis1.BackColor = Color.Transparent;
            listView1_SelectedIndexChanged(sender, e);
        }

        private void linkLabel3_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            button_Emphasis2.BackColor = Color.Transparent;
            listView1_SelectedIndexChanged(sender, e);
        }
        //auto rip
        private void button3_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            if (VobcharImagesComparer.CompareImages == null)
                VobcharImagesComparer.CompareImages = new List<VobCharImage>();
            button1.Enabled = button2.Enabled = groupBox1.Enabled = groupBox2.Enabled = groupBox3.Enabled =
                groupBox4.Enabled = groupBox5.Enabled = false;
            label_status.Visible = progressBar1.Visible = true;
            progressBar1.Maximum = listView1.Items.Count;
            for (int i = (int)numericUpDown1.Value; i < listView1.Items.Count; i++)
            {
                Frm_ImageText frm = new Frm_ImageText(((ListViewItem_VobPack)listView1.Items[i]).VobSubMergedPack,
                    comboBox1.SelectedIndex);
                try
                {
                    frm.ShowDialog(this);
                }
                catch { }
                if (frm.OK)
                {
                    ((ListViewItem_VobPack)listView1.Items[i]).SetText(frm.EnteredText);
                }
                else
                {
                    break;
                }
                label_status.Text = resources.GetString("Status_Ripping") + " " + i + " / " + listView1.Items.Count;
                progressBar1.Value = i;
                listView1.Refresh();
                progressBar1.Refresh();
                label_status.Refresh();
            }
            button4.Enabled = VobcharImagesComparer.CompareImages.Count > 0;
            if (VobcharImagesComparer.CompareImages.Count > 0)
            {
                MessageDialogResult result = MessageDialog.ShowMessage(resources.GetString("Message_DoneDoYouWantToSaveCharMatrix"),
                    resources.GetString("MessageCaption_Done"), MessageDialogButtons.OkNo,
                    MessageDialogIcon.Question, false, resources.GetString("Button_Yes"), resources.GetString("Button_No"));
                if (result == MessageDialogResult.Ok)
                {
                    button4_Click(null, null);
                }
            }
            button1.Enabled = button2.Enabled = groupBox1.Enabled = groupBox2.Enabled = groupBox3.Enabled =
          groupBox4.Enabled = groupBox5.Enabled = true;
            label_status.Visible = progressBar1.Visible = false;
            Cursor = Cursors.Default;
        }
        //save matrix
        private void button4_Click(object sender, EventArgs e)
        {
            SaveFileDialog sav = new SaveFileDialog();
            sav.Filter = "(*.mx)|*.mx";
            if (sav.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {

                try
                {
                    VobCharsMatrixFile file = new VobCharsMatrixFile();
                    file.CompareImages = VobcharImagesComparer.CompareImages;
                    FileStream fs = new FileStream(sav.FileName, FileMode.Create, FileAccess.Write);
                    BinaryFormatter formatter = new BinaryFormatter();
                    formatter.Serialize(fs, file);
                    fs.Close();
                }
                catch (Exception ex)
                {
                    MessageDialog.ShowErrorMessage(resources.GetString("Message_CantSave") + "\n\n" + ex.Message,
                      resources.GetString("MessageCaption_Error"));
                }
            }
        }
        //load matrix
        private void button5_Click(object sender, EventArgs e)
        {
            OpenFileDialog op = new OpenFileDialog();
            op.Filter = "(*.mx)|*.mx";
            if (op.ShowDialog(this) == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    FileStream fs = new FileStream(op.FileName, FileMode.Open, FileAccess.Read);
                    BinaryFormatter formatter = new BinaryFormatter();
                    VobCharsMatrixFile file = (VobCharsMatrixFile)formatter.Deserialize(fs);
                    VobcharImagesComparer.CompareImages = file.CompareImages;
                    fs.Close();
                }
                catch (Exception ex)
                {
                    MessageDialog.ShowErrorMessage(resources.GetString("Message_CantLoad") + "\n\n" + ex.Message,
                        resources.GetString("MessageCaption_Error"));
                }
            }
            if (VobcharImagesComparer.CompareImages == null)
                VobcharImagesComparer.CompareImages = new List<VobCharImage>();
            button4.Enabled = VobcharImagesComparer.CompareImages.Count > 0;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = System.Windows.Forms.DialogResult.Cancel;
            Close();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            Help.ShowHelp(this, ".\\" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name +
                "\\Help.chm", HelpNavigator.KeywordIndex, "How to, Rip subtitles from Matroska (mkv)");
        }
    }
}
