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

public class UIPoseContainer : MonoBehaviour
{
    public DataType Type;
    public string PoseName;
    public KeyframeData KeyframeData;
    public TMPro.TMP_InputField NameLabel;

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

    public static UIPoseContainer CreateNew(string poseName, KeyframeData poseData, bool forceOverride)
    {
        if (poseData == null) return null;
        if (string.IsNullOrEmpty(poseName))
        {
            Error.Log(Color.red, "Name the pose first");
            return null;
        }

        if (UI.SaveLoadPanel.GetPoseByName(poseName, out var savedPose))
        {
            if (!forceOverride)
            {
                Error.Log(Color.red, "Preset with this name already exists");
                return null;
            }
        }
        else
        {
            savedPose = Instantiate(SharedResources.Instance.UIPoseContainer, UI.PosePresetToggle.content);
            UI.SaveLoadPanel.AddPose(savedPose);
        }

        savedPose.Init(poseName, poseData);

        return savedPose;
    }

    public void Init(string poseName, KeyframeData poseData)
    {
        NameLabel.text = poseName;
        NameLabel.interactable = false;
        KeyframeData = poseData;
        transform.SetAsFirstSibling();
    }

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

        if (UI.SaveLoadPanel.GetPoseByName(poseName, out var savedPose))
        {
            Error.Log(Color.red, "Preset with this name already exists");
            return;
        }
        else
        {
            savedPose = Instantiate(SharedResources.Instance.UIPoseContainer, UI.PosePresetToggle.content);
            savedPose.NameLabel.text = poseName;
            UI.SaveLoadPanel.AddPose(savedPose);
        }

        savedPose.Save();
    }

    public void Save()
    {
        Error.Log(Color.blue, $"Saving pose...");

        var poseData = Main.SelectedObject.SerializeFrame();
        string poseName = NameLabel.text;
        string fileName = Path.GetFullPath(Path.Combine(Settings.SavePoseDirectory, $"{poseName}.pose"));

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

        Init(poseName, poseData);
    }

    public void Load()
    {
        if (Main.SelectedObject == null) return;

        if (Input.GetKey(KeyCode.LeftShift))
        {
            LoadAdvanced();
        }
        else
        {
            Main.SelectedObject.PastePose(KeyframeData, new PoseLoadOptions(true));
        }
    }

    public void LoadAdvanced()
    {
        if (Main.SelectedObject == null) return;

        UIPopupPastePanel.Create(
            (pasteOption) => { Main.SelectedObject.PastePose(KeyframeData, pasteOption); Debug.Log(pasteOption.Root); },
            () => { });
        
    }

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

        string path = Path.GetFullPath(Path.Combine(Settings.SavePoseDirectory, $"{PoseName}.pose"));
        if (File.Exists(path))
            File.Delete(path);

        Error.Log(Color.yellow, "Deleted " + path);
    }
}