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 UISaveLoadPanel SaveLoadPanel => ModelViewerInterface.GetInstance().CanvasContainer.SaveLoadPanel;
    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 (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, SaveLoadPanel.ScrollScene.content);
            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 (SaveLoadPanel.GetSceneByName(sceneName, out var savedScene))
        {
            Error.Log(Color.red, "Preset with this name already exists");
            return;
        }
        else
        {
            savedScene = Instantiate(SharedResources.Instance.UISceneContainer, SaveLoadPanel.ScrollScene.content);
            savedScene.NameLabel.text = sceneName;
            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(UISaveLoadPanel.SaveSceneDirectory, $"{sceneData.Filename}.scene"));

        try
        {
            var settings = new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Auto, DefaultValueHandling = DefaultValueHandling.Ignore };
            var json = JsonConvert.SerializeObject(sceneData, typeof(SceneSerializable), 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(UISaveLoadPanel.SaveSceneDirectory, $"{SceneData.Filename}.scene"));
        if (File.Exists(path))
            File.Delete(path);
        
        Error.Log(Color.yellow, "Deleted " + path);
    }
}