#region Copyright

/* -----------------------------------------------------------------------------
 *  Copyright © 2024 • Chomp Studios • All Rights Reserved
 * -----------------------------------------------------------------------------
 *  Date: 30/10/2024
 *  -----------------------------------------------------------------------------
 *  Description: Code behind the "Notes" Window
 *  -----------------------------------------------------------------------------
 */

#endregion

#if UNITY_EDITOR

#region Imports

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Linq;
using UnityEditor;
using UnityEngine;
using Workflow_Toolkit.Utilities;
using Workflow_Toolkit.Utilities.Enums;
using Workflow_Toolkit.Utilities.Localisation;
using Workflow_Toolkit.Utilities.Saving;
#if UNITY_6000_5_OR_NEWER
using Unity.Scripting.LifecycleManagement;
#endif

#endregion

namespace Workflow_Toolkit.Tools {
    public class Notes : EditorWindow {
        [MenuItem("Tools/Workflow Toolkit/Tools/Notes", false, 100)]
        public static void ShowWindow() {
            UIElements.DisplayWindow<Notes>(
                LocalisationManager.Instance.GetString(LocalizationKeys.WINDOW_TITLE_NOTES),
                new Vector2(300, 300)
            );
            LoggingElements.LogInfo("Notes Tool Launched");
        }

        #region Note Data

        [Serializable]
        private class Note {
            public string name;
            public string contents;
            public long createdTicks;

            // Absolute path of the file this note was last saved to (null if never saved)
            public string filePath;

            public DateTime Created => new(createdTicks, DateTimeKind.Local);
        }

        private const string DEFAULT_NOTE_NAME = "New Note";
        private const string FALLBACK_FILE_NAME = "Untitled";
        private const double AUTO_SAVE_DELAY = 1.0;

        [NoAutoStaticsCleanup]
        private static readonly Regex TextNotePattern = new(
            @"^Date:[ \t]*(?<date>.*?)\r?\n\s*Note Name:[ \t]*(?<name>.*?)\r?\n\s*Contents:[ ]?(?<contents>[\s\S]*)$"
        );

        [NoAutoStaticsCleanup]
        private static readonly HashSet<string> ReservedFileNames = new(StringComparer.OrdinalIgnoreCase) {
            "CON", "PRN", "AUX", "NUL",
            "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9",
            "LPT1", "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9"
        };

        #endregion

        #region Directory and Note Config

        private string _exportDir = "";

        // Serialized so notes survive script recompiles / domain reloads
        [SerializeField] private List<Note> _notes = new();

        [SerializeField] private bool _hasLoadedFromDisk;

        // Files written by the last save, used to clean up after renames, removals and file type changes
        private readonly HashSet<string> _knownFiles = new(StringComparer.OrdinalIgnoreCase);

        private static string DefaultExportDir => Path.GetFullPath(Path.Combine(Application.dataPath, "..", "Notes"));

        #endregion

        #region Save and Export Settings

        private readonly string[] _fileType = { "txt", "json" };

        private int _selectedFileTypeIndex;

        private bool _saveNote;
        private bool _autoSave;

        private bool _isDirty;
        private double _lastEditTime;

        private string FileExtension => _selectedFileTypeIndex == 0 ? ".txt" : ".json";

        #endregion

        #region UI

        private bool _showSettings = true;
        private bool _showNotes = true;
        private bool _showExport = true;

        private UIElements _uiElements;
        private FileElements _fileElements;

        private Vector2 _scrollPos;

        #endregion

        #region GUI Functions

        private void OnEnable() {
            _uiElements = CreateInstance<UIElements>();
            _fileElements = CreateInstance<FileElements>();

            _exportDir = SaveLoad.LoadFilePath(ToolName.NOTES, "ExportDir", null);
            if (string.IsNullOrEmpty(_exportDir)) _exportDir = DefaultExportDir;

            _saveNote = SaveLoad.LoadBoolean(ToolName.NOTES, "SaveNotes");
            _autoSave = SaveLoad.LoadBoolean(ToolName.NOTES, "AutoSave", true);

            _selectedFileTypeIndex =
                Mathf.Clamp(SaveLoad.LoadInt(ToolName.NOTES, "FileType", 0), 0, _fileType.Length - 1);

            if (_saveNote) EnsureLoadedFromDisk();

            _knownFiles.Clear();
            foreach (var note in _notes.Where(note => !string.IsNullOrEmpty(note.filePath)))
                _knownFiles.Add(note.filePath);

            Undo.undoRedoPerformed += OnUndoRedo;
        }

        private void OnDisable() {
            Undo.undoRedoPerformed -= OnUndoRedo;

            if (_isDirty && _saveNote && _autoSave) WriteNotes();

            SaveLoad.SaveFilePath(ToolName.NOTES, "ExportDir", _exportDir);

            SaveLoad.SaveBoolean(ToolName.NOTES, "SaveNotes", _saveNote);
            SaveLoad.SaveBoolean(ToolName.NOTES, "AutoSave", _autoSave);

            SaveLoad.SaveInt(ToolName.NOTES, "FileType", _selectedFileTypeIndex);
            PlayerPrefs.Save();

            if (_uiElements != null) DestroyImmediate(_uiElements);
            if (_fileElements != null) DestroyImmediate(_fileElements);
        }

        // Called ~10 times per second; saves once the user has stopped typing for AUTO_SAVE_DELAY seconds
        private void OnInspectorUpdate() {
            if (!_isDirty || !_saveNote || !_autoSave) return;
            if (EditorApplication.timeSinceStartup - _lastEditTime < AUTO_SAVE_DELAY) return;

            WriteNotes();
        }

        private void OnUndoRedo() {
            MarkDirty();
            Repaint();
        }

        private void OnGUI() {
            UIElements.TrackHover(this);

            _scrollPos = EditorGUILayout.BeginScrollView(_scrollPos);
            _uiElements.DrawHeader(
                LocalisationManager.Instance.GetString(LocalizationKeys.WINDOW_TITLE_NOTES),
                LocalisationManager.Instance.GetString(LocalizationKeys.HEADER_DESCRIPTION_NOTES)
            );

            DrawSettingsUI();
            DrawNotesUI();
            DrawExportButton();

            _uiElements.DrawFooter();
            EditorGUILayout.EndScrollView();
        }

        private void DrawSettingsUI() {
            _uiElements.BeginSection(
                LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_SETTINGS),
                ref _showSettings,
                WorkflowStyles.SettingsIcon
            );

            if (_showSettings) {
                EditorGUI.BeginChangeCheck();
                _saveNote = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_SAVE_NOTES),
                    _saveNote, LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SAVE_NOTES)
                );

                EditorGUI.BeginDisabledGroup(!_saveNote);
                _autoSave = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_AUTO_SAVE),
                    _autoSave,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_AUTO_SAVE)
                );
                if (EditorGUI.EndChangeCheck() && _saveNote) {
                    EnsureLoadedFromDisk();
                    MarkDirty();
                }

                EditorGUI.BeginChangeCheck();
                _selectedFileTypeIndex = TooltipElements.Popup(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_FILE_TYPE),
                    _selectedFileTypeIndex,
                    _fileType,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_FILE_TYPE)
                );
                // Saving again converts the existing files to the new type
                if (EditorGUI.EndChangeCheck()) {
                    _hasLoadedFromDisk = false;
                    MarkDirty();
                }

                EditorGUI.EndDisabledGroup();

                GUILayout.Space(6);
                GUILayout.Label(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_EXPORT_PATH),
                    WorkflowStyles.Caption);

                if (_uiElements.PathField(
                        _fileElements.GetLastFolders(_exportDir),
                        _exportDir,
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SELECT_EXPORT_PATH))
                   ) {
                    var newDir = _fileElements.SelectDirectory(
                        LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_SELECT_EXPORT_PATH),
                        _exportDir
                    );
                    ChangeExportDir(newDir);
                    GUIUtility.ExitGUI();
                }
            }

            _uiElements.EndSection();
        }

        private void DrawNotesUI() {
            var newNoteButton = new GUIContent(
                " " + LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_NEW_NOTE),
                WorkflowStyles.PlusIcon,
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_NEW_NOTE)
            );

            if (_uiElements.BeginSection(
                    LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_NOTES),
                    ref _showNotes,
                    WorkflowStyles.NotesIcon,
                    _notes.Count.ToString(),
                    newNoteButton)
               ) {
                AddNote();
                _showNotes = true;
            }

            if (_showNotes) {
                if (_notes.Count == 0) {
                    GUILayout.Space(10);
                    GUILayout.Label(LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_NEW_NOTE),
                        WorkflowStyles.Footer);
                    GUILayout.Space(10);
                }

                var removeIndex = -1;
                var contentPlaceholder = LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_NOTE_CONTENT)
                    .TrimEnd(':', ' ');

                EditorGUI.BeginChangeCheck();

                // Newest notes are displayed first
                for (var i = _notes.Count - 1; i >= 0; i--) {
                    var note = _notes[i];

                    _uiElements.BeginInset();
                    EditorGUILayout.BeginHorizontal();

                    note.name = EditorGUILayout.TextField(note.name, WorkflowStyles.TitleField);
                    TooltipElements.WriteTooltip(
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_EDIT_NOTE_NAME));

                    GUILayout.Space(4);
                    if (_uiElements.IconButton(
                            WorkflowStyles.TrashIcon,
                            "X",
                            LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_REMOVE_NOTE),
                            true)
                       )
                        removeIndex = i;

                    EditorGUILayout.EndHorizontal();

                    GUILayout.Label(note.Created.ToString("g", CultureInfo.CurrentCulture), WorkflowStyles.Caption);

                    note.contents = TooltipElements.TextArea(
                        note.contents,
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_EDIT_NOTE_CONTENT),
                        GUILayout.MinHeight(80)
                    );
                    if (string.IsNullOrEmpty(note.contents))
                        WorkflowStyles.DrawPlaceholder(GUILayoutUtility.GetLastRect(), contentPlaceholder);

                    _uiElements.EndInset();
                }

                if (EditorGUI.EndChangeCheck()) MarkDirty();

                if (removeIndex >= 0) RemoveNote(removeIndex);
            }

            _uiElements.EndSection();
        }

        private void DrawExportButton() {
            _uiElements.BeginSection(
                LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_EXPORT),
                ref _showExport,
                WorkflowStyles.ExportIcon
            );

            if (_showExport)
                if (_uiElements.PrimaryButton(new GUIContent(
                        LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_EXPORT_NOTES),
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_EXPORT_NOTES)))
                   ) {
                    if (WriteNotes())
                        EditorUtility.DisplayDialog(
                            LocalisationManager.Instance.GetString(LocalizationKeys.WINDOW_TITLE_NOTES),
                            LocalisationManager.Instance.GetString(LocalizationKeys.SUCCESS_EXPORT_NOTES),
                            "OK"
                        );
                    GUIUtility.ExitGUI();
                }

            _uiElements.EndSection();
        }

        #endregion

        #region Note Management

        private void MarkDirty() {
            _isDirty = true;
            _lastEditTime = EditorApplication.timeSinceStartup;
        }

        private void AddNote() {
            Undo.RecordObject(this, "Add Note");
            _notes.Add(new Note {
                name = GetUniqueNoteName(DEFAULT_NOTE_NAME),
                contents = "",
                createdTicks = DateTime.Now.Ticks
            });
            MarkDirty();
        }

        private void RemoveNote(int index) {
            var note = _notes[index];

            // Only ask for confirmation when there is something to lose
            if (!string.IsNullOrEmpty(note.contents) && !EditorUtility.DisplayDialog(
                    LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_REMOVE_NOTE),
                    $"{LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_REMOVE_NOTE)}\n\n\"{note.name}\"",
                    LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_REMOVE_NOTE),
                    "Cancel")) {
                GUIUtility.ExitGUI();
                return;
            }

            // The note's file is removed on the next save, so Undo can bring it back
            Undo.RecordObject(this, "Remove Note");
            _notes.RemoveAt(index);
            MarkDirty();
            GUIUtility.ExitGUI();
        }

        private string GetUniqueNoteName(string baseName) {
            var existing = new HashSet<string>(_notes.Select(note => note.name), StringComparer.OrdinalIgnoreCase);
            if (!existing.Contains(baseName)) return baseName;

            var suffix = 2;
            while (existing.Contains($"{baseName} {suffix}")) suffix++;
            return $"{baseName} {suffix}";
        }

        private void ChangeExportDir(string newDir) {
            if (string.IsNullOrEmpty(newDir)) return;

            newDir = Path.GetFullPath(newDir);
            if (string.Equals(newDir, Path.GetFullPath(_exportDir), StringComparison.OrdinalIgnoreCase)) return;

            // Leave the files in the old folder alone; notes in the new folder are merged in on the next save
            _exportDir = newDir;
            _hasLoadedFromDisk = false;
            _knownFiles.Clear();
            foreach (var note in _notes) note.filePath = null;
            MarkDirty();
        }

        #endregion

        #region Saving and Loading

        /// <summary>
        ///     Writes every note to the export directory, removing files left behind by renamed or removed notes.
        /// </summary>
        /// <returns>True if all notes were written successfully.</returns>
        private bool WriteNotes() {
            _isDirty = false;

            // Never overwrite notes on disk that haven't been loaded into the window yet
            EnsureLoadedFromDisk();

            try {
                Directory.CreateDirectory(_exportDir);

                var targetPaths = BuildTargetPaths();
                var targetSet = new HashSet<string>(targetPaths, StringComparer.OrdinalIgnoreCase);

                foreach (var stalePath in _knownFiles.Where(path => !targetSet.Contains(path) && File.Exists(path))
                             .ToList())
                    File.Delete(stalePath);

                for (var i = 0; i < _notes.Count; i++) {
                    WriteNote(_notes[i], targetPaths[i]);
                    _notes[i].filePath = targetPaths[i];
                }

                _knownFiles.Clear();
                _knownFiles.UnionWith(targetSet);

                LoggingElements.LogInfo($"Saved {_notes.Count} note(s) to {_exportDir}");
                return true;
            }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException || e is ArgumentException ||
                                      e is NotSupportedException) {
                Debug.LogError($"[Workflow Toolkit] Failed to save notes to \"{_exportDir}\": {e.Message}");
                LoggingElements.LogException(e);
                return false;
            }
        }

        private void WriteNote(Note note, string path) {
            var date = note.Created.ToString("o", CultureInfo.InvariantCulture);

            if (_selectedFileTypeIndex == 0) {
                var newLine = Environment.NewLine;
                File.WriteAllText(path,
                    $"Date: {date}{newLine}{newLine}" +
                    $"Note Name: {note.name}{newLine}{newLine}" +
                    $"Contents: {note.contents}"
                );
            }
            else {
                var noteJson = new JObject(
                    new JProperty("Date", date),
                    new JProperty("Note Name", note.name),
                    new JProperty("Contents", note.contents)
                );
                File.WriteAllText(path, noteJson.ToString());
            }
        }

        /// <summary>
        ///     Builds a unique, filesystem-safe file path for every note, in list order.
        /// </summary>
        private List<string> BuildTargetPaths() {
            var exportDir = Path.GetFullPath(_exportDir);
            var usedNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
            var paths = new List<string>(_notes.Count);

            foreach (var note in _notes) {
                var baseName = SanitiseFileName(note.name);
                var fileName = baseName;
                var suffix = 2;
                while (!usedNames.Add(fileName)) fileName = $"{baseName} ({suffix++})";

                paths.Add(Path.Combine(exportDir, fileName + FileExtension));
            }

            return paths;
        }

        private static string SanitiseFileName(string name) {
            if (string.IsNullOrWhiteSpace(name)) return FALLBACK_FILE_NAME;

            var invalidChars = Path.GetInvalidFileNameChars();
            var sanitised = new string(name.Select(c => invalidChars.Contains(c) ? '_' : c).ToArray())
                .Trim()
                .TrimEnd('.');

            if (string.IsNullOrEmpty(sanitised)) return FALLBACK_FILE_NAME;
            return ReservedFileNames.Contains(sanitised) ? "_" + sanitised : sanitised;
        }

        private void EnsureLoadedFromDisk() {
            if (_hasLoadedFromDisk) return;
            _hasLoadedFromDisk = true;
            LoadNotesFromDisk();
        }

        /// <summary>
        ///     Loads previously saved notes of the current file type from the export directory.
        /// </summary>
        private void LoadNotesFromDisk() {
            if (string.IsNullOrEmpty(_exportDir) || !Directory.Exists(_exportDir)) return;

            string[] files;
            try {
                files = Directory.GetFiles(_exportDir);
            }
            catch (Exception e) when (e is IOException || e is UnauthorizedAccessException) {
                LoggingElements.LogWarning($"Could not read notes from {_exportDir}: {e.Message}");
                return;
            }

            var loaded = new List<Note>();

            foreach (var path in files) {
                if (!string.Equals(Path.GetExtension(path), FileExtension, StringComparison.OrdinalIgnoreCase))
                    continue;

                try {
                    var note = _selectedFileTypeIndex == 0 ? ParseTextNote(path) : ParseJsonNote(path);
                    if (note == null) continue;

                    note.filePath = Path.GetFullPath(path);
                    loaded.Add(note);
                }
                catch (Exception e) {
                    LoggingElements.LogWarning($"Skipped unreadable note file {path}: {e.Message}");
                }
            }

            // Existing notes go first so they keep their original file names
            loaded.Sort((a, b) => a.createdTicks.CompareTo(b.createdTicks));
            _notes.InsertRange(0, loaded);
            foreach (var note in loaded) _knownFiles.Add(note.filePath);

            if (loaded.Count > 0) LoggingElements.LogInfo($"Loaded {loaded.Count} note(s) from {_exportDir}");
        }

        private static Note ParseTextNote(string path) {
            var match = TextNotePattern.Match(File.ReadAllText(path));
            if (!match.Success) return null;

            return new Note {
                name = match.Groups["name"].Value.Trim(),
                contents = match.Groups["contents"].Value.TrimEnd('\r', '\n'),
                createdTicks = ParseDate(match.Groups["date"].Value.Trim(), path).Ticks
            };
        }

        private static Note ParseJsonNote(string path) {
            var json = JObject.Parse(File.ReadAllText(path));
            var name = json["Note Name"];
            if (name == null) return null;

            var dateToken = json["Date"];
            var created = dateToken?.Type == JTokenType.Date
                ? ToLocal(dateToken.Value<DateTime>())
                : ParseDate(dateToken?.ToString(), path);

            return new Note {
                name = name.ToString(),
                contents = json["Contents"]?.ToString() ?? "",
                createdTicks = created.Ticks
            };
        }

        // Accepts the ISO 8601 dates written now, plus culture-formatted dates written by older versions
        private static DateTime ParseDate(string value, string path) {
            if (DateTime.TryParse(value, CultureInfo.InvariantCulture, DateTimeStyles.AssumeLocal, out var date) ||
                DateTime.TryParse(value, CultureInfo.CurrentCulture, DateTimeStyles.AssumeLocal, out date))
                return ToLocal(date);

            return File.GetCreationTime(path);
        }

        private static DateTime ToLocal(DateTime date) {
            return date.Kind == DateTimeKind.Utc ? date.ToLocalTime() : DateTime.SpecifyKind(date, DateTimeKind.Local);
        }

        #endregion
    }
}
#endif