using Newtonsoft.Json;
using System;
using System.IO;
using System.Text;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Cryville.Crtr.Config {
	public class ConfigScene : MonoBehaviour {
		[SerializeField]
		Transform m_content;

		[SerializeField]
		SettingsPanel m_genericConfigPanel;

		[SerializeField]
		InputConfigPanel m_inputConfigPanel;

		public Ruleset ruleset;
		RulesetConfig _rscfg;

		void Awake() {
			ChartPlayer.etor = new PdtEvaluator();
			FileInfo file = new FileInfo(
				Game.GameDataPath + "/rulesets/" + Settings.Default.LoadRuleset
			);
			if (!file.Exists) {
				Popup.Create("Ruleset for the chart not found\nMake sure you have imported the ruleset");
				ReturnToMenu();
				return;
			}
			DirectoryInfo dir = file.Directory;
			using (StreamReader reader = new StreamReader(file.FullName, Encoding.UTF8)) {
				ruleset = JsonConvert.DeserializeObject<Ruleset>(reader.ReadToEnd(), new JsonSerializerSettings() {
					MissingMemberHandling = MissingMemberHandling.Error
				});
				if (ruleset.format != Ruleset.CURRENT_FORMAT) throw new FormatException("Invalid ruleset file version");
				ruleset.LoadPdt(dir);
			}
			FileInfo cfgfile = new FileInfo(
				Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
			);
			if (!cfgfile.Exists) {
				if (!cfgfile.Directory.Exists) cfgfile.Directory.Create();
				_rscfg = new RulesetConfig();
			}
			else {
				using (StreamReader cfgreader = new StreamReader(cfgfile.FullName, Encoding.UTF8)) {
					_rscfg = JsonConvert.DeserializeObject<RulesetConfig>(cfgreader.ReadToEnd(), new JsonSerializerSettings() {
						MissingMemberHandling = MissingMemberHandling.Error
					});
				}
			}

			m_genericConfigPanel.Target = _rscfg.generic;

			var proxy = new InputProxy(ruleset.Root, null);
			proxy.LoadFrom(_rscfg.inputs);
			m_inputConfigPanel.proxy = proxy;
			Game.InputManager.Activate();
		}

		public void SwitchCategory(GameObject cat) {
			foreach (Transform c in m_content) {
				c.gameObject.SetActive(false);
			}
			cat.SetActive(true);
		}

		public void SaveAndReturnToMenu() {
			Game.InputManager.Deactivate();
			m_inputConfigPanel.proxy.SaveTo(_rscfg.inputs);
			m_inputConfigPanel.proxy.Dispose();
			FileInfo cfgfile = new FileInfo(
				Game.GameDataPath + "/config/rulesets/" + Settings.Default.LoadRulesetConfig
			);
			using (StreamWriter cfgwriter = new StreamWriter(cfgfile.FullName, false, Encoding.UTF8)) {
				cfgwriter.Write(JsonConvert.SerializeObject(_rscfg, Game.GlobalJsonSerializerSettings));
			}
			ReturnToMenu();
		}
		public void ReturnToMenu() {
			GameObject.Find("Master").GetComponent<Master>().ShowMenu();
#if UNITY_5_5_OR_NEWER
			SceneManager.UnloadSceneAsync("Config");
#elif UNITY_5_3_OR_NEWER
			SceneManager.UnloadScene("Config");
#endif
		}
	}
}
