using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Windows;
using System.Windows.Input;
using System.Windows.Markup;

namespace QCLVR;

public partial class DataminerWin : Window, IComponentConnector
{
	private string inputFile;

	public ConsoleTextBox output;

	private bool autoFortmatdescriptor;

	public DataminerWin(string InputFilePath)
	{
		InitializeComponent();
		inputFile = InputFilePath;
		autoFortmatdescriptor = false;
		output = new ConsoleTextBox(ConsoleOut);
		Console.SetOut(output);
	}

	private void FilePathBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
	{
		FDPathBox.SelectAll();
		FDPathBox.Focus();
	}

	private void OptionBox_MouseDoubleClick(object sender, MouseButtonEventArgs e)
	{
		OptionsTextBox.SelectAll();
		OptionsTextBox.Focus();
	}

	private void FilePathBox_KeyDown(object sender, KeyEventArgs e)
	{
		if (e.Key == Key.Return)
		{
			runDataminer();
		}
	}

	private void OutputDataReceived(object sender, DataReceivedEventArgs e)
	{
		Console.WriteLine(e.Data);
	}

	private void AutoFD_Checked(object sender, RoutedEventArgs e)
	{
		autoFortmatdescriptor = true;
		FDPathBox.IsEnabled = false;
		selectFDBtn.IsEnabled = false;
	}

	private void AutoFD_Unchecked(object sender, RoutedEventArgs e)
	{
		autoFortmatdescriptor = false;
		FDPathBox.IsEnabled = true;
		selectFDBtn.IsEnabled = true;
	}

	private void SelectFDBtn_Click(object sender, RoutedEventArgs e)
	{
		FDPathBox.Text = main.SelectFile();
	}

	private void RunBtn_Click(object sender, RoutedEventArgs e)
	{
		runDataminer();
	}

	private void runDataminer()
	{
		string text = FDPathBox.Text;
		Process process = new Process();
		process.StartInfo.UseShellExecute = false;
		process.StartInfo.FileName = "Dataminer";
		process.StartInfo.Arguments = " " + OptionsTextBox.Text + " " + inputFile;
		if (autoFortmatdescriptor)
		{
			process.StartInfo.Arguments += " -autoFD";
		}
		else
		{
			if (!File.Exists(text))
			{
				MessageBox.Show("File does not exist");
				return;
			}
			ProcessStartInfo startInfo = process.StartInfo;
			startInfo.Arguments = startInfo.Arguments + " " + text;
		}
		process.StartInfo.CreateNoWindow = true;
		process.StartInfo.RedirectStandardOutput = true;
		process.OutputDataReceived += OutputDataReceived;
		Console.WriteLine(process.StartInfo.FileName + process.StartInfo.Arguments);
		try
		{
			process.Start();
			process.BeginOutputReadLine();
		}
		catch (Exception ex)
		{
			Console.WriteLine($"ERROR: {ex.ToString()}");
		}
	}

	private void Window_Closing(object sender, CancelEventArgs e)
	{
		base.Owner.IsEnabled = true;
	}
}
