﻿#region Copyright

/* -----------------------------------------------------------------------------
 *  Copyright © 2024 • Chomp Studios • All Rights Reserved
 * -----------------------------------------------------------------------------
 *  Date: 30/10/2024
 *  -----------------------------------------------------------------------------
 *  Description: Code to save and load options
 *  -----------------------------------------------------------------------------
 */

#endregion

#if UNITY_EDITOR

#region Imports

using System.Collections.Generic;
using UnityEngine;
using Workflow_Toolkit.Utilities.Enums;

#endregion

namespace Workflow_Toolkit.Utilities.Saving {
    public static class SaveLoad {
        private static string ProjectName => Application.productName;

        private static string PrefixedKey(ToolName tool, string key) {
            return $"{ProjectName}_{tool}_{key}";
        }

        public static void SaveColor(ToolName tool, string key, Color color) {
            var colorString = ColorUtility.ToHtmlStringRGBA(color);
            PlayerPrefs.SetString(PrefixedKey(tool, key), colorString);
            PlayerPrefs.Save();
        }


        public static void SaveFilePath(ToolName tool, string key, string filePath) {
            PlayerPrefs.SetString(PrefixedKey(tool, key), filePath);
            PlayerPrefs.Save();
        }

        public static void SaveBoolean(ToolName tool, string key, bool value) {
            PlayerPrefs.SetInt(PrefixedKey(tool, key), value ? 1 : 0);
            PlayerPrefs.Save();
        }

        public static void SaveInt(ToolName tool, string key, int value) {
            PlayerPrefs.SetInt(PrefixedKey(tool, key), value);
            PlayerPrefs.Save();
        }

        public static void SaveString(ToolName tool, string key, string value) {
            PlayerPrefs.SetString(PrefixedKey(tool, key), value);
            PlayerPrefs.Save();
        }

        public static void SaveCameras(ToolName tool, string key, List<Camera> cameras) {
            var cameraNames = new List<string>();
            foreach (var camera in cameras)
                if (camera != null)
                    cameraNames.Add(camera.name);

            var json = JsonUtility.ToJson(new CameraList { cameras = cameraNames });
            PlayerPrefs.SetString(PrefixedKey(tool, key), json);
            PlayerPrefs.Save();
        }

        public static Color LoadColor(ToolName tool, string key, Color defaultColor) {
            var colorString =
                PlayerPrefs.GetString(PrefixedKey(tool, key), ColorUtility.ToHtmlStringRGBA(defaultColor));
            return ColorUtility.TryParseHtmlString($"#{colorString}", out var color) ? color : defaultColor;
        }

        public static string LoadFilePath(ToolName tool, string key, string defaultPath) {
            return PlayerPrefs.HasKey(PrefixedKey(tool, key))
                ? PlayerPrefs.GetString(PrefixedKey(tool, key))
                : defaultPath;
        }

        public static int LoadInt(ToolName tool, string key, int defaultValue) {
            return PlayerPrefs.GetInt(PrefixedKey(tool, key), defaultValue);
        }

        public static string LoadString(ToolName tool, string key, string defaultValue) {
            return PlayerPrefs.HasKey(PrefixedKey(tool, key))
                ? PlayerPrefs.GetString(PrefixedKey(tool, key))
                : defaultValue;
        }

        public static bool LoadBoolean(ToolName tool, string key, bool defaultValue = false) {
            return PlayerPrefs.GetInt(PrefixedKey(tool, key), defaultValue ? 1 : 0) == 1;
        }

        public static List<Camera> LoadCameras(ToolName tool, string key) {
            var json = PlayerPrefs.GetString(PrefixedKey(tool, key), "");
            if (string.IsNullOrEmpty(json)) return new List<Camera>();

            var cameraList = JsonUtility.FromJson<CameraList>(json);
            var cameras = new List<Camera>();

            foreach (var cameraName in cameraList.cameras) {
                var foundCamera = GameObject.Find(cameraName)?.GetComponent<Camera>();
                if (foundCamera != null)
                    cameras.Add(foundCamera);
                else
                    Debug.LogWarning($"Camera '{cameraName}' not found in the scene.");
            }

            return cameras;
        }

        public static void ClearSetting(ToolName tool, string key) {
            PlayerPrefs.DeleteKey(PrefixedKey(tool, key));
            PlayerPrefs.Save();
        }

        public static void ClearAllSettings() {
            var toolKeys = new Dictionary<ToolName, string[]> {
                {
                    ToolName.POST_BUILD_ACTIONS,
                    new[] {
                        "BuildsDir", "OutputDir", "AddFiles", "SelectedStageIndex", "SelectedFileNameOrderIndex",
                        "SelectedTimestampIndex", "ZipCompressionIndex", "FilePaths", "DestinationFolders",
                        "IncludeTimestamp", "BuildDevelopment", "BuildAllowDebugging", "BuildCleanCache",
                        "BuildStrictMode", "BuildCompressionIndex"
                    }
                },
                { ToolName.NOTES, new[] { "ExportDir", "SaveNotes", "AutoSave", "FileType" } }, {
                    ToolName.SCRIPT_COUNTER,
                    new[] {
                        "FileExtension", "SelectedDir", "DisplayScriptNames", "IncludeHiddenFiles",
                        "SortAlphabetically", "ShowFileSize"
                    }
                }, {
                    ToolName.FANCY_SCREENSHOT,
                    new[] {
                        "OutputDir", "ApplyBorder", "ApplyResolutionMultiplier", "BorderColor", "BorderThickness",
                        "ResolutionMultiplier", "CustomName", "AttachedCameras", "MultiCamera"
                    }
                }
            };

            foreach (var tool in toolKeys)
            foreach (var key in tool.Value)
                PlayerPrefs.DeleteKey(PrefixedKey(tool.Key, key));

            PlayerPrefs.Save();
            Debug.Log("All custom settings cleared for Unity Workflow Toolkit.");
        }
    }
}

#endif