using Newtonsoft.Json;
using System;
using System.IO;
using System.Linq;
using UnityEngine;

public class UISceneContainer : MonoBehaviour
{
    public SceneSerializable SceneData;
    public TMPro.TMP_InputField NameLabel;
    public TMPro.TMP_Text DateLabel;
    public TMPro.TMP_Text VersionLabel;

    static ModelViewerInterface UI => ModelViewerInterface.GetInstance();
    static ModelViewerMain Main => ModelViewerMain.GetInstance();

    public static UISceneContainer CreateNew(SceneSerializable sceneData, bool forceOverride)
    {
        if(sceneData == null) return null;
        if (string.IsNullOrEmpty(sceneData.Filename))
        {
            Error.Log(Color.red, "Name the scene first");
            return null;
        }

        if (UI.SaveLoadPanel.GetSceneByName(sceneData.Filename, out var savedScene))
        {
            if (!forceOverride)
            {
                Error.Log(Color.red, "Preset with this name already exists");
                return null;
            }
        }
        else
        {
            savedScene = Instantiate(SharedResources.Instance.UISceneContainer, UI.ScenePresetToggle.content);
            UI.SaveLoadPanel.AddScene(savedScene);
        }

        savedScene.Init(sceneData);

        return savedScene;
    }

    public void Init(SceneSerializable scene)
    {
        NameLabel.text = scene.Filename;
        NameLabel.interactable = false;
        DateLabel.text = "Save date: " + scene.Date;
        VersionLabel.text = "Version: " + scene.Version;
        SceneData = scene;
        transform.SetAsFirstSibling();
    }

    public void SaveNew()
    {
        var sceneName = NameLabel.text;

        if (UI.SaveLoadPanel.GetSceneByName(sceneName, out var savedScene))
        {
            Error.Log(Color.red, "Preset with this name already exists");
            return;
        }
        else
        {
            savedScene = Instantiate(SharedResources.Instance.UISceneContainer, UI.ScenePresetToggle.content);
            savedScene.NameLabel.text = sceneName;
            UI.SaveLoadPanel.AddScene(savedScene);
        }

        savedScene.Save();
    }

    public void Save(bool silenceMessage = false)
    {
        if (!silenceMessage)
        {
            Error.Log(Color.blue, $"Saving scene...");
        }

        var sceneData = Main.SaveScene();
        sceneData.Filename = NameLabel.text;
        string fileName = Path.GetFullPath(Path.Combine(Settings.SaveSceneDirectory, $"{sceneData.Filename}.scene"));

        try
        {
            var settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto, DefaultValueHandling = DefaultValueHandling.Ignore };
            var json = JsonConvert.SerializeObject(sceneData, Formatting.Indented, settings);
            File.WriteAllText(fileName, json);
            if (!silenceMessage)
            {
                Error.Log(Color.green, $"Scene saved to {fileName}");
            }
        }
        catch (Exception ex)
        {
            Error.Log(Color.red, ex.Message);
            return;
        }

        Init(sceneData);
    }

    public void Load()
    {
        StartCoroutine(Main.LoadScene(SceneData));
    }

    public void Delete()
    {
        Destroy(this.gameObject);

        string path = Path.GetFullPath(Path.Combine(Settings.SaveSceneDirectory, $"{SceneData.Filename}.scene"));
        if (File.Exists(path))
            File.Delete(path);
        
        Error.Log(Color.yellow, "Deleted " + path);
    }
}