using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using QC.QMSLPhone;

namespace QFDT_Components;

public partial class QMSL_Log : UserControl, IComponentConnector
{
	private enum State
	{
		START,
		STOP
	}

	private delegate void PrintDebugMessageCB(uint time, ushort logLevel, string msg);

	public Phone phone;

	public string QMSLLogPath = "C:\\Qualcomm\\QDART\\QFDT\\QMSLLog.txt";

	private State state = State.STOP;

	public QMSL_Log()
	{
		InitializeComponent();
	}

	private void Start_Click(object sender, RoutedEventArgs e)
	{
		if (state == State.STOP)
		{
			if (phone != null)
			{
				phone.StartLogging(QMSLLogPath);
				phone.ConfigureLibraryTextLogCallBack(PrintQMSLTextLog);
				state = State.START;
				Start.Content = "Stop";
			}
		}
		else if (state == State.START && phone != null)
		{
			phone.StopLogging();
			state = State.STOP;
			Start.Content = "Start";
		}
	}

	private void Stop_Click(object sender, RoutedEventArgs e)
	{
	}

	public void SetLanguage(string culture)
	{
		ResourceDictionary resourceDictionary = new ResourceDictionary();
		try
		{
			resourceDictionary.Source = new Uri(Thread.GetDomain().BaseDirectory + "\\Resources\\UI_" + culture + ".xaml", UriKind.Absolute);
		}
		catch
		{
			resourceDictionary.Source = new Uri(Thread.GetDomain().BaseDirectory + "..\\Resources\\UI_en-US.xaml", UriKind.Absolute);
		}
		base.Resources.MergedDictionaries.Clear();
		base.Resources.MergedDictionaries.Add(resourceDictionary);
	}

	private void Show_Click(object sender, RoutedEventArgs e)
	{
		if (File.Exists(QMSLLogPath))
		{
			Process process = new Process();
			process.StartInfo.FileName = QMSLLogPath;
			process.Start();
		}
	}

	public void PrintQMSLTextLog(uint time, ushort logLevel, string msg)
	{
		PrintDebugMessage(time, logLevel, msg);
	}

	public void PrintDebugMessage(uint time, ushort logLevel, string msg)
	{
		if (txtDebugMessage.Dispatcher.CheckAccess())
		{
			string text = "";
			if ((logLevel & 0x200) == 512)
			{
				text = "LOG_C_HIGH_LEVEL_START";
			}
			else if ((logLevel & 0x4000) == 16384)
			{
				text = "LOG_C_HIGH_LEVEL_STOP";
			}
			else if ((logLevel & 1) == 1)
			{
				text = "LOG_IO";
			}
			else if ((logLevel & 2) == 2)
			{
				text = "LOG_FN";
			}
			else if ((logLevel & 4) == 4)
			{
				text = "LOG_RET";
			}
			new Run(time + " " + text + ", " + msg + "\r\n", txtDebugMessage.CaretPosition.DocumentEnd);
			txtDebugMessage.ScrollToEnd();
		}
		else
		{
			PrintDebugMessageCB method = PrintDebugMessage;
			base.Dispatcher.BeginInvoke(method, time, logLevel, msg);
		}
	}

	private void Clear_Click(object sender, RoutedEventArgs e)
	{
		txtDebugMessage.Document.Blocks.Clear();
	}
}
