using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace Supertonic.WinForms
{
    public partial class fMain : Form
    {
        private TextToSpeech _tts;

        public fMain()
        {
            InitializeComponent();
        }

        private async void btnGenerate_Click(object sender, EventArgs e)
        {
            try
            {
                string text = txtInput.Text;
                string lang = cmbLang.SelectedItem?.ToString() ?? "en";
                string stylePath = txtStylePath.Text;
                int totalStep = (int)numSteps.Value;
                float speed = (float)numSpeed.Value;

                if (string.IsNullOrWhiteSpace(text))
                {
                    MessageBox.Show("Please enter text.");
                    return;
                }

                if (_tts == null)
                {
                    Log("Loading TTS model...");
                    string onnxDir = "assets/onnx"; // This should be updated if assets are moved
                    _tts = await System.Threading.Tasks.Task.Run(() => Helper.LoadTextToSpeech(onnxDir, false));
                    Log("TTS model loaded.");
                }

                Log($"Generating speech: \"{text}\" ({lang})");
                
                var style = Helper.LoadVoiceStyle(new List<string> { stylePath }, true);
                
                var result = await System.Threading.Tasks.Task.Run(() => _tts.Call(text, lang, style, totalStep, speed));
                
                string saveDir = "results";
                if (!Directory.Exists(saveDir)) Directory.CreateDirectory(saveDir);

                string fname = $"{Helper.SanitizeFilename(text, 20)}_{DateTime.Now:HHmmss}.wav";
                string outputPath = Path.Combine(saveDir, fname);
                
                Helper.WriteWavFile(outputPath, result.wav, _tts.SampleRate);
                Log($"Saved: {outputPath}");
                
                // Play the generated WAV file immediately
                Helper.PlayWavFile(outputPath);
                
                MessageBox.Show($"Synthesis completed successfully!\nSaved to: {outputPath}");
            }
            catch (Exception ex)
            {
                Log($"Error: {ex.Message}");
                MessageBox.Show($"Error: {ex.Message}");
            }
        }

        private void Log(string msg)
        {
            if (txtLog.InvokeRequired)
            {
                txtLog.Invoke(new Action(() => Log(msg)));
                return;
            }
            txtLog.AppendText($"[{DateTime.Now:HH:mm:ss}] {msg}\r\n");
            txtLog.SelectionStart = txtLog.Text.Length;
            txtLog.ScrollToCaret();
        }

        private void fMain_Load(object sender, EventArgs e)
        {
            cmbLang.Items.AddRange(Languages.Available);
            cmbLang.SelectedIndex = 0;
            
            // Set default style path if exists
            string defaultStyle = "assets/voice_styles/M1.json";
            if (File.Exists(defaultStyle)) txtStylePath.Text = defaultStyle;
        }
    }
}
