using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Diagnostics;
using System.IO;

namespace Sownloader
{
    public partial class Converter : Form
    {
        private Thread convertingThread;
        private string input, output; // Only to prevent invoking in other thread

        private FileHandler.INIClass inifile;

        public Converter()
        {
            InitializeComponent();
            inifile = new FileHandler.INIClass();
        }

        #region File select
        private void btnInput_Click(object sender, EventArgs e)
        {
            ofdMediaFile.ShowDialog();
        }

        private void btnOutput_Click(object sender, EventArgs e)
        {
            sfdMediaFile.ShowDialog();
        }

        private void ofdMediaFile_FileOk(object sender, CancelEventArgs e)
        {
            tbInput.Text = ofdMediaFile.FileName;
        }

        private void sfdMediaFile_FileOk(object sender, CancelEventArgs e)
        {
            tbOutput.Text = sfdMediaFile.FileName;
        }
        #endregion  
        /// <summary>
        /// Handles tbInput.Text changes and tbOutput.Text changes
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tbInput_TextChanged(object sender, EventArgs e)
        {
            btnStartConverting.Enabled = (tbInput.Text.Length > 0 && tbOutput.Text.Length > 0) ? true : false;
            btnOutput.Enabled = (tbInput.Text.Length > 0) ? true : false;

            input = tbInput.Text;
            output = tbOutput.Text;

            if (tbInput.Text.EndsWith(".m4a"))
                sfdMediaFile.Filter = "MP3 Audio(*.mp3) | *.mp3";
            else
            {
                sfdMediaFile.Filter = "MP3 Audio(*.mp3) | *.mp3|MP4 Audio (*.m4a)|*.m4a";
                sfdMediaFile.DefaultExt = ".mp3";
            }
        }
        #region Converting
        private void btnStartConverting_Click(object sender, EventArgs e)
        {
            convertingThread = new Thread(Convert);
            convertingThread.Start();
        }
        private void Convert()
        {
            try
            {
                using (Process FFmpeg = new Process())
                {
                    FFmpeg.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    FFmpeg.StartInfo.FileName = Path.Combine(Application.StartupPath, "ffmpeg.exe");
                    FFmpeg.StartInfo.UseShellExecute = false;
                    FFmpeg.StartInfo.CreateNoWindow = false;
                    string tempFile = Path.Combine(Path.GetTempPath(), Hilfsklassen.GenerateRandomString(5) + Path.GetExtension(input));

                    File.Copy(input, tempFile);


                    string outputExtension = output.Substring(output.Length - 4);

                    string codec = "";

                    switch (outputExtension)
                    {
                        case ".mp3":
                            codec = "-i " + tempFile + " -f mp3 -b:a " + inifile.BITRATE + " -acodec libmp3lame " + tempFile.Substring(0, tempFile.Length - 4) + ".mp3";
                            break;
                        case ".m4a":
                            codec = "-i " + tempFile + " -vn -c:a copy " + tempFile.Substring(0, tempFile.Length - 4) + ".m4a";
                            break;
                        default:
                            break;
                    }

                    FFmpeg.StartInfo.Arguments = codec;

                    FFmpeg.Start();

                    while (!FFmpeg.HasExited)
                    {

                    }

                    FFmpeg.Dispose();
                    FFmpeg.Close();
                    File.Copy(tempFile.Substring(0, tempFile.Length - 4) + outputExtension, output);
                    File.Delete(tempFile);
                    File.Delete(tempFile.Substring(0, tempFile.Length - 4) + outputExtension);
                }

                

            }
            catch (Exception ex)
            {
                MessageBox.Show("Converting has been canceled" + Environment.NewLine + Environment.NewLine + ex.Message,
                    "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                convertingThread.Abort();
            }
            MessageBox.Show("Converting has been finished!", "Finished", MessageBoxButtons.OK, MessageBoxIcon.Information);
            convertingThread.Abort();
        }
        #endregion
    }
}
