using Cryville.EEW.Core;
using Cryville.EEW.CWAOpenData;
using Cryville.EEW.CWAOpenData.Model;
using Cryville.EEW.CWAOpenData.TTS;
using Cryville.EEW.GlobalQuake;
using Cryville.EEW.JMAAtom;
using Cryville.EEW.JMAAtom.TTS;
using Cryville.EEW.NOAA;
using Cryville.EEW.NOAA.TTS;
using Cryville.EEW.Report;
using Cryville.EEW.Unity.Map;
using Cryville.EEW.Unity.UI;
using Cryville.EEW.UpdateChecker;
using Cryville.EEW.Wolfx;
using Cryville.EEW.Wolfx.TTS;
using System;
using System.Collections.Concurrent;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;

namespace Cryville.EEW.Unity {
	sealed class Worker : MonoBehaviour {
		public static Worker Instance { get; private set; }

		[SerializeField] CameraController m_cameraController;
		[SerializeField] MapElementManager m_mapElementManager;
		[SerializeField] EventOngoingListView m_ongoingEventList;
		[SerializeField] EventGroupListView m_historyEventGroupList;

		GroupingCoreWorker _worker;
		CancellationTokenSource _cancellationTokenSource;

		void Awake() {
			if (Instance != null) {
				Destroy(this);
				throw new InvalidOperationException("Duplicate worker.");
			}
			Instance = this;

			App.Init();

			_worker = new(new TTSWorker());
			_cancellationTokenSource = new();
		}

		void Start() {
			LocalizedResources.Init(new LocalizedResourcesManager());
			RegisterViewModelGenerators(_worker);
			RegisterTTSMessageGenerators(_worker);
			BuildWorkers();
			_worker.RVMGeneratorContext = SharedSettings.Instance;
			_worker.TTSMessageGeneratorContext = SharedSettings.Instance;
			_ongoingReportManager.Changed += OnOngoingReported;
			_worker.Reported += OnReported;
			_worker.GroupUpdated += OnGroupUpdated;
			_worker.GroupRemoved += OnGroupRemoved;
			Task.Run(() => _worker.RunAsync(_cancellationTokenSource.Token));
			Task.Run(() => _ongoingReportManager.RunAsync(_cancellationTokenSource.Token));
		}

		void OnDestroy() {
			_cancellationTokenSource.Cancel();
			_worker.Dispose();
			_ongoingReportManager.Dispose();
		}

		static void RegisterViewModelGenerators(CoreWorker worker) {
			worker.RegisterViewModelGenerator(new CENCEarthquakeRVMGenerator());
			worker.RegisterViewModelGenerator(new CENCEEWRVMGenerator());
			worker.RegisterViewModelGenerator(new CWAEarthquakeRVMGenerator());
			worker.RegisterViewModelGenerator(new CWAEEWRVMGenerator());
			worker.RegisterViewModelGenerator(new CWATsunamiRVMGenerator());
			worker.RegisterViewModelGenerator(new FujianEEWRVMGenerator());
			worker.RegisterViewModelGenerator(new GlobalQuakeRVMGenerator());
			worker.RegisterViewModelGenerator(new JMAAtomRVMGenerator());
			worker.RegisterViewModelGenerator(new JMAEEWRVMGenerator());
			worker.RegisterViewModelGenerator(new NOAAAtomRVMGenerator());
			worker.RegisterViewModelGenerator(new SichuanEEWRVMGenerator());
			worker.RegisterViewModelGenerator(new VersionRVMGenerator());
		}
		static void RegisterTTSMessageGenerators(CoreWorker worker) {
			worker.RegisterTTSMessageGenerator(new CENCEarthquakeTTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new CENCEEWTTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new CWAEarthquakeTTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new CWAEEWTTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new CWATsunamiTTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new FujianEEWTTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new JMAAtomTTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new JMAEEWTTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new NOAATTSMessageGenerator());
			worker.RegisterTTSMessageGenerator(new SichuanEEWTTSMessageGenerator());
		}

		WolfxWorker _wolfxWorker;
		JMAAtomWorker _jmaWorker;
		CWAReportWorker<Tsunami> _cwa14Worker;
		CWAReportWorker<Earthquake> _cwa15Worker;
		CWAReportWorker<Earthquake> _cwa16Worker;
		GlobalQuakeWorker _gqWorker;
		NOAAAtomWorker _ntwcWorker;
		NOAAAtomWorker _ptwcWorker;
		UpdateCheckerWorker _updateChecker;
		void BuildWorkers() {
#if UNITY_EDITOR
			_worker.AddWorker(_wolfxWorker = new WolfxWorker(new Uri("ws://localhost:9995/wolfx")));
			_worker.AddWorker(_jmaWorker = new JMAAtomWorker(new Uri("http://localhost:9095/eqvol.xml")));
			_worker.AddWorker(_cwa14Worker = new CWAReportWorker<Tsunami>(new Uri("http://localhost:9095/E-A0014-001.json"), "1"));
			_worker.AddWorker(_cwa15Worker = new CWAReportWorker<Earthquake>(new Uri("http://localhost:9095/E-A0015-001.json"), "1"));
			_worker.AddWorker(_cwa16Worker = new CWAReportWorker<Earthquake>(new Uri("http://localhost:9095/E-A0016-001.json"), "1"));
			_worker.AddWorker(_ntwcWorker = new NOAAAtomWorker(new("http://localhost:9095/PAAQAtom.xml")));
			// _worker.AddWorker(_gqWorker = new GlobalQuakeWorker("localhost", 38000));
#else
			// TODO
#endif
			if (_updateChecker == null) _worker.AddWorker(_updateChecker = new(typeof(Worker).Assembly.GetName().Version?.ToString(3) ?? "", "unity"));
		}

		readonly OngoingReportManager _ongoingReportManager = new();
		readonly ConcurrentQueue<Action> _uiActionQueue = new();
		void OnReported(object sender, ReportViewModel e) {
			Debug.Log(e);
			_ongoingReportManager.Report(e);
			_uiActionQueue.Enqueue(() => m_mapElementManager.SetSelected(e));
		}
		void OnOngoingReported(ReportViewModel item, CollectionChangeAction action) {
			if (action == CollectionChangeAction.Add) {
				_uiActionQueue.Enqueue(() => {
					m_mapElementManager.AddOngoing(item);
					m_ongoingEventList.Add(item);
				});
			}
			else if (action == CollectionChangeAction.Remove) {
				_uiActionQueue.Enqueue(() => {
					m_mapElementManager.RemoveOngoing(item);
					m_ongoingEventList.Remove(item);
				});
			}
		}
		void OnGroupUpdated(object sender, ReportGroup e) {
			_uiActionQueue.Enqueue(() => m_historyEventGroupList.UpdateGroup(e));
		}
		void OnGroupRemoved(object sender, ReportGroup e) {
			_uiActionQueue.Enqueue(() => m_historyEventGroupList.RemoveGroup(e));
		}
		public void SetSelected(ReportViewModel e) {
			m_mapElementManager.SetSelected(e);
			m_cameraController.OnMapElementUpdated();
		}
		public void SetCurrent(ReportViewModel e) {
			m_mapElementManager.SetCurrent(e);
			m_cameraController.OnMapElementUpdated();
		}

		void Update() {
			while (_uiActionQueue.TryDequeue(out var action)) {
				action();
				m_cameraController.OnMapElementUpdated();
			}
		}
	}
}
