/*
Copyright 2019 Dr. Thomas Benjamin Senior, Michael Zoeller 

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

using System;
using System.Collections.Generic;
using Newtonsoft.Json;
using UnityEngine;
using UnityEngine.SceneManagement;

using UnityEngine.XR;

namespace EyeSkills
{
    public class ConfigBase
    {
        public string id()
        {
            return GetType().FullName;
        }

        public string PlayerPrefsId()
        {
            string myId="EyeSkills.Config-" + NetworkManager.instance.GetUUID() + "-" + id();
            return myId;
        }

        public ConfigBase()
        {

            //Debug.Log("AHA " + id());
            // constructor is called during serialization! see LoadConfig
            if (ConfigManager.instance)
                ConfigManager.instance.LoadConfig(this);
        }

        public void Load()
        {
            // populate from PlayerPrefs
            var json = PlayerPrefs.GetString(PlayerPrefsId());
            if (json != "")
                JsonConvert.PopulateObject(json, this);

            // request network config
            NetworkManager.instance.Send("request_config", "{\"id\": \"" + id() + "\"}");
        }

        public void Save()
        {
            if (ConfigManager.instance)
                ConfigManager.instance.SaveConfig(this);
        }

        public void Sync()
        {
            if (ConfigManager.instance)
                ConfigManager.instance.SaveConfig(this, true);
        }
    }

    public class ConfigBasePerScene : ConfigBase
    {
        public new string id()
        {
            return GetType().FullName + SceneManager.GetActiveScene();
        }
    }

    public class ConfigManager : MonoBehaviour
    {
        // singleton like access pattern
        public static ConfigManager instance;

        private void Awake()
        {
            // singleton like access pattern
            if (instance == null)
                instance = this;
            else if (instance != this)
                Destroy(gameObject);

            DontDestroyOnLoad(this);
        }

        Dictionary<string, ConfigBase> ConfigBases = new Dictionary<string, ConfigBase>();

        void OnEnable()
        {
            SceneManager.sceneLoaded += OnSceneLoaded;
            SceneManager.sceneUnloaded += OnSceneUnloaded;
        }

        void OnDisable()
        {
            SceneManager.sceneLoaded -= OnSceneLoaded;
            SceneManager.sceneUnloaded -= OnSceneUnloaded;
        }

        void OnSceneUnloaded(Scene scene)
        {
            Debug.Log("OnSceneUnloaded: " + scene.name);

            if (scene.name == "Menu" || scene.name == "Bootstrap" || scene.name == "Lobby" )//|| !XRSettings.enabled)
                return;

            foreach (KeyValuePair<string, ConfigBase> entry in ConfigBases)
                SaveConfig(entry.Value);

            ConfigBases.Clear();
        }

        void OnSceneLoaded(Scene scene, LoadSceneMode mode)
        {
            Debug.Log("OnSceneLoaded: " + scene.name);

            if (scene.name == "Menu" || scene.name == "Bootstrap" || scene.name == "Lobby")
                return;

            foreach (KeyValuePair<string, ConfigBase> entry in ConfigBases)
                entry.Value.Load();
        }

        public void LoadConfig(ConfigBase config)
        {
            // PlayerPrefs needs to be used from main thread, so we postphone and resume in OnSceneLoaded
            ConfigBases[config.id()] = config;
        }

        public void SaveConfig(ConfigBase config, bool sync = false)
        {
            var json = JsonConvert.SerializeObject(config);
            Debug.Log("SAVE: " + json);

            if (!sync)
            {
                Debug.Log("Config: Saving config " + config.id());
                PlayerPrefs.SetString(config.PlayerPrefsId(), json);
            }
            else
                Debug.Log("Config: Syncing with server.");

            // send config to server
            NetworkManager.instance.Send("set_config", "{\"id\": \"" + config.id() + "\", \"config\": " + json + "}");
        }

        public void ConfigReply(string id, string config)
        {
            Debug.Log("Config: Config reply from server for " + id);

            if (!ConfigBases.ContainsKey(id))
                return;

            if (config == "")
                // server does not know this config yet, so we upload it
                SaveConfig(ConfigBases[id], true);
            else
                JsonConvert.PopulateObject(config, ConfigBases[id]);
        }
    }
}
