#region Copyright

/* -----------------------------------------------------------------------------
 *  Copyright © 2024 • Chomp Studios • All Rights Reserved
 * -----------------------------------------------------------------------------
 *  Date: 30/10/2024
 *  -----------------------------------------------------------------------------
 *  Description: Post Build Actions tool code
 *  -----------------------------------------------------------------------------
 */

#endregion

#if UNITY_EDITOR

#region Imports

using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Security.Cryptography;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
using Workflow_Toolkit.Utilities;
using Workflow_Toolkit.Utilities.Builder;
using Workflow_Toolkit.Utilities.Enums;
using Workflow_Toolkit.Utilities.Localisation;
using Workflow_Toolkit.Utilities.Saving;
using CompressionLevel = System.IO.Compression.CompressionLevel;

#endregion

namespace Workflow_Toolkit.Tools {
    public class PostBuildActions : EditorWindow {
        private void OnEnable() {
            _gameName = Application.productName;

            _uiElements = CreateInstance<UIElements>();
            _fileElements = CreateInstance<FileElements>();

            _buildsDir = SaveLoad.LoadFilePath(ToolName.POST_BUILD_ACTIONS, "BuildsDir", null);
            _outputDir = SaveLoad.LoadFilePath(ToolName.POST_BUILD_ACTIONS, "OutputDir", null);

            _addFiles = SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "AddFiles");

            _buildDevelopment = SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "BuildDevelopment");
            _buildAllowDebugging = SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "BuildAllowDebugging");
            _buildCleanCache = SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "BuildCleanCache");
            _buildStrictMode = SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "BuildStrictMode");

            _excludeDoNotShip = SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "ExcludeDoNotShip", true);
            _createChecksum = SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "CreateChecksum");
            _bumpVersionOnBuild = SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "BumpVersionOnBuild");
            _versionPartIndex = SaveLoad.LoadInt(ToolName.POST_BUILD_ACTIONS, "VersionPartIndex", 2);

            LoadNameTags();
            _separatorIndex = SaveLoad.LoadInt(ToolName.POST_BUILD_ACTIONS, "NameSeparatorIndex", 0);
            _zipCompressionIndex = SaveLoad.LoadInt(ToolName.POST_BUILD_ACTIONS, "ZipCompressionIndex", 2);
            _buildTargetIndex = SaveLoad.LoadInt(ToolName.POST_BUILD_ACTIONS, "BuildTargetChoice", 0);
            _buildCompressionIndex = SaveLoad.LoadInt(ToolName.POST_BUILD_ACTIONS, "BuildCompressionIndex", 0);

            var serializedFilePaths = SaveLoad.LoadString(ToolName.POST_BUILD_ACTIONS, "FilePaths", string.Empty);
            var serializedDestFolders =
                SaveLoad.LoadString(ToolName.POST_BUILD_ACTIONS, "DestinationFolders", string.Empty);

            if (!string.IsNullOrEmpty(serializedFilePaths))
                _filePaths = serializedFilePaths
                    .Split(new[] { FilePathDelimiter }, StringSplitOptions.RemoveEmptyEntries).ToList();
            if (!string.IsNullOrEmpty(serializedDestFolders))
                _destinationFolders = serializedDestFolders
                    .Split(new[] { FilePathDelimiter }, StringSplitOptions.RemoveEmptyEntries).ToList();
        }

        private void OnDisable() {
            SaveLoad.SaveFilePath(ToolName.POST_BUILD_ACTIONS, "BuildsDir", _buildsDir);
            SaveLoad.SaveFilePath(ToolName.POST_BUILD_ACTIONS, "OutputDir", _outputDir);

            SaveLoad.SaveBoolean(ToolName.POST_BUILD_ACTIONS, "AddFiles", _addFiles);

            SaveLoad.SaveBoolean(ToolName.POST_BUILD_ACTIONS, "BuildDevelopment", _buildDevelopment);
            SaveLoad.SaveBoolean(ToolName.POST_BUILD_ACTIONS, "BuildAllowDebugging", _buildAllowDebugging);
            SaveLoad.SaveBoolean(ToolName.POST_BUILD_ACTIONS, "BuildCleanCache", _buildCleanCache);
            SaveLoad.SaveBoolean(ToolName.POST_BUILD_ACTIONS, "BuildStrictMode", _buildStrictMode);

            SaveLoad.SaveBoolean(ToolName.POST_BUILD_ACTIONS, "ExcludeDoNotShip", _excludeDoNotShip);
            SaveLoad.SaveBoolean(ToolName.POST_BUILD_ACTIONS, "CreateChecksum", _createChecksum);
            SaveLoad.SaveBoolean(ToolName.POST_BUILD_ACTIONS, "BumpVersionOnBuild", _bumpVersionOnBuild);
            SaveLoad.SaveInt(ToolName.POST_BUILD_ACTIONS, "VersionPartIndex", _versionPartIndex);

            SaveNameTags();
            SaveLoad.SaveInt(ToolName.POST_BUILD_ACTIONS, "NameSeparatorIndex", _separatorIndex);
            SaveLoad.SaveInt(ToolName.POST_BUILD_ACTIONS, "ZipCompressionIndex", _zipCompressionIndex);
            SaveLoad.SaveInt(ToolName.POST_BUILD_ACTIONS, "BuildTargetChoice", _buildTargetIndex);

            SaveLoad.SaveInt(ToolName.POST_BUILD_ACTIONS, "BuildCompressionIndex", _buildCompressionIndex);

            var serializedFilePaths = string.Join(FilePathDelimiter, _filePaths);
            var serializedDestFolders = string.Join(FilePathDelimiter, _destinationFolders);

            SaveLoad.SaveString(ToolName.POST_BUILD_ACTIONS, "FilePaths", serializedFilePaths);
            SaveLoad.SaveString(ToolName.POST_BUILD_ACTIONS, "DestinationFolders", serializedDestFolders);

            PlayerPrefs.Save();

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

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

            _scrollPosition = EditorGUILayout.BeginScrollView(_scrollPosition);
            _uiElements.DrawHeader(
                LocalisationManager.Instance.GetString(LocalizationKeys.WINDOW_TITLE_POST_BUILD_ACTIONS),
                LocalisationManager.Instance.GetString(LocalizationKeys.HEADER_DESCRIPTION_POST_BUILD_ACTIONS));
            DrawFolderSelectionUI();
            DrawSettingsUI();
            DrawBuildButton();
            _uiElements.DrawFooter();
            EditorGUILayout.EndScrollView();
        }

        [MenuItem("Tools/Workflow Toolkit/Tools/Post Build Actions", false, 100)]
        public static void ShowWindow() {
            UIElements.DisplayWindow<PostBuildActions>(
                LocalisationManager.Instance.GetString(LocalizationKeys.WINDOW_TITLE_POST_BUILD_ACTIONS),
                new Vector2(300, 300));
            LoggingElements.LogInfo(LocalisationManager.Instance.GetString(LocalizationKeys.LOG_INFO_TOOL_LAUNCHED));
        }

        #region Build Config

        private string _buildsDir = "";
        private string _outputDir = "";

        private bool _addFiles;
        private bool _zipFile;
        private bool _unityPackage;

        private int _compressionType;

        private bool _excludeDoNotShip = true;
        private bool _createChecksum;

        #endregion

        #region File and Folder Handling

        private List<string> _filePaths = new();
        private List<string> _destinationFolders = new();

        private const string FilePathDelimiter = "|";

        #endregion

        #region Game Metadata

        private string _gameName;
        private bool _nameFile;

        #endregion

        #region File Naming

        private readonly string[] _developmentStage = { "Development", "Alpha", "Beta", "Testing", "Release" };
        private readonly string[] _timestampPresets = { "dd-MM-yy_HH-mm", "yyyy-MM-dd", "MM-dd-yyyy_HH-mm" };

        // The zip name is built from tags, in order. Index 0 means "none" for both lists.
        private readonly string[] _brackets = { "", "[]", "()", "{}" };
        private readonly string[] _separators = { " ", "_", "-", "" };

        private enum TagType {
            GameName,
            Stage,
            Version,
            Timestamp,
            Text
        }

        [Serializable]
        private class NameTag {
            public TagType Type;
            public bool Enabled = true;
            public int Brackets;

            // Stage: which stage. Timestamp: which format.
            public int Option;

            // Game Name: a name to use instead of the Product Name. Version: the prefix ("v"). Text: the text itself.
            public string Text = "";
        }

        [Serializable]
        private class NameTagList {
            public List<NameTag> Tags = new();
        }

        private List<NameTag> _nameTags = new();
        private int _separatorIndex;
        private int _selectedTagIndex = -1;

        // Tag dragging
        private readonly List<Rect> _tagRects = new();
        private int _pressedTagIndex = -1;
        private bool _draggingTag;
        private Vector2 _dragStartMouse;
        private int _dropIndex = -1;
        private float _tagAreaWidth = 280f;
        private GUIStyle _tagStyle;
        private GUIStyle _previewStyle;

        private readonly string[] _zipCompressionAmount = { "None", "Fast", "Optimal" };
        private int _zipCompressionIndex = 2;

        // Index 0 follows the project's current platform (File > Build Profiles), so a mobile game builds an .apk
        private readonly string[] _buildTarget = { "", "Standalone Windows", "Standalone Linux", "Android", "IOS" };
        private int _buildTargetIndex;

        private readonly string[] _buildCompressionValue = { "None", "Lz4", "Lz4HC" };
        private int _buildCompressionIndex;

        private readonly string[] _versionParts = { "Major", "Minor", "Patch" };
        private int _versionPartIndex = 2;
        private bool _bumpVersionOnBuild;

        #endregion

        #region UI

        private UIElements _uiElements;
        private FileElements _fileElements;
        private BuildOptions _buildOptions;
        private Vector2 _scrollPosition;

        private bool _showAttachments = true;
        private bool _showSettings = true;
        private bool _showFileSettings = true;
        private bool _showBuildSettings = true;
        private bool _showPlayerBuildSettings = true;
        private bool _showBuild = true;
        private bool _showNamingSettings = true;

        private bool _buildDevelopment;
        private bool _buildAllowDebugging;
        private bool _buildCleanCache;
        private bool _buildStrictMode;

        #endregion


        #region GUI Functions

        private void DrawFolderSelectionUI() {
            _uiElements.BeginSection(
                LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_ATTACHMENTS),
                ref _showAttachments,
                WorkflowStyles.FolderIcon,
                tooltip: LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_ATTACH_BUILD_PATH)
            );

            if (_showAttachments) {
                GUILayout.Label(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_BUILD_PATH),
                    WorkflowStyles.Caption);
                if (_uiElements.PathField(DisplayPath(_buildsDir), _buildsDir,
                        LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_SELECT_BUILD_DIRECTORY))) {
                    _buildsDir = _fileElements.SelectDirectory(
                        LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_SELECT_BUILD_DIRECTORY),
                        _buildsDir);
                    GUIUtility.ExitGUI();
                }

                GUILayout.Space(4);
                GUILayout.Label(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_EXPORT_PATH),
                    WorkflowStyles.Caption);
                if (_uiElements.PathField(DisplayPath(_outputDir), _outputDir,
                        LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_SELECT_EXPORT_PATH))) {
                    _outputDir = _fileElements.SelectDirectory(
                        LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_SELECT_EXPORT_PATH), _outputDir);
                    GUIUtility.ExitGUI();
                }
            }

            _uiElements.EndSection();
        }

        private string DisplayPath(string path) {
            return string.IsNullOrEmpty(path)
                ? LocalisationManager.Instance.GetString(LocalizationKeys.NONE_SELECTED)
                : _fileElements.GetLastFolders(path);
        }

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

            if (_showSettings) {
                DrawBuildSettingsUI();
                DrawPlayerSettingsUI();
                DrawFileSettingsUI();
                DrawNamingSettingsUI();
            }

            _uiElements.EndSection();
        }

        private void DrawNamingSettingsUI() {
            _uiElements.BeginSubSection(
                LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_NAMING),
                ref _showNamingSettings,
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_NAMING_SETTINGS)
            );

            if (_showNamingSettings) {
                DrawNameTagsUI();
                DrawVersionUI();
            }

            _uiElements.EndSubSection();
        }


        #region Name Tags

        private void DrawNameTagsUI() {
            _uiElements.GroupLabel(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_FILE_NAME));
            GUILayout.Label(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_NAME_TAGS_HINT),
                WorkflowStyles.Caption);
            GUILayout.Space(4);

            DrawTagChips();
            DrawSelectedTag();

            GUILayout.Space(4);
            EditorGUI.BeginChangeCheck();
            _separatorIndex = TooltipElements.Popup(
                LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_SEPARATOR),
                _separatorIndex, new[] {
                    LocalisationManager.Instance.GetString(LocalizationKeys.OPTION_SPACE), "_", "-",
                    LocalisationManager.Instance.GetString(LocalizationKeys.OPTION_NONE)
                },
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SEPARATOR));
            if (EditorGUI.EndChangeCheck())
                SaveLoad.SaveInt(ToolName.POST_BUILD_ACTIONS, "NameSeparatorIndex", _separatorIndex);

            DrawNamePreview();
        }

        // The tags as pills that wrap onto new lines. Click one to select it, drag one to move it.
        private void DrawTagChips() {
            const float chipHeight = 24f;
            const float gap = 6f;

            var e = Event.current;
            if (_tagStyle == null) {
                _tagStyle = new GUIStyle(EditorStyles.label) {
                    alignment = TextAnchor.MiddleCenter, fontSize = 11, padding = new RectOffset(12, 12, 0, 0)
                };
                _tagStyle.normal.textColor = Color.white;
            }

            var contents = _nameTags.Select(tag => new GUIContent(ChipText(tag), TagTypeName(tag.Type))).ToList();
            var addContent = new GUIContent("+  " +
                                            LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_ADD_TEXT_TAG),
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_ADD_TEXT_TAG));

            // Lay out against the width measured on the last repaint, so Layout and Repaint agree
            var localRects = new List<Rect>();
            var x = 0f;
            var y = 0f;

            Rect Place(GUIContent content) {
                var width = Mathf.Min(_tagStyle.CalcSize(content).x, _tagAreaWidth);
                if (x > 0f && x + width > _tagAreaWidth) {
                    x = 0f;
                    y += chipHeight + gap;
                }

                var rect = new Rect(x, y, width, chipHeight);
                x += width + gap;
                return rect;
            }

            foreach (var content in contents) localRects.Add(Place(content));
            var addLocal = Place(addContent);

            var area = GUILayoutUtility.GetRect(0, y + chipHeight, GUILayout.ExpandWidth(true));
            if (e.type == EventType.Repaint && area.width > 1f && Mathf.Abs(area.width - _tagAreaWidth) > 0.5f) {
                _tagAreaWidth = area.width;
                Repaint();
            }

            _tagRects.Clear();
            foreach (var rect in localRects) _tagRects.Add(Offset(rect, area.position));
            var addRect = Offset(addLocal, area.position);

            HandleTagMouse(e);

            if (e.type == EventType.Repaint) {
                for (var i = 0; i < _nameTags.Count; i++) {
                    var tag = _nameTags[i];
                    var hover = GUIUtility.hotControl == 0 && _tagRects[i].Contains(e.mousePosition);
                    var alpha = (tag.Enabled ? 1f : 0.4f) * (_draggingTag && i == _pressedTagIndex ? 0.3f : 1f);
                    DrawChip(_tagRects[i], contents[i], TagColour(tag.Type), i == _selectedTagIndex, hover, alpha);
                }

                var addHover = GUIUtility.hotControl == 0 && addRect.Contains(e.mousePosition);
                WorkflowStyles.DrawRect(addRect, WithAlpha(WorkflowStyles.AccentText, addHover ? 0.12f : 0f), 12);
                WorkflowStyles.DrawRect(addRect,
                    WithAlpha(addHover ? WorkflowStyles.AccentText : WorkflowStyles.StrongBorder, 0.8f), 12, 1);
                var previous = GUI.contentColor;
                GUI.contentColor = addHover ? WorkflowStyles.AccentText : WorkflowStyles.MutedText;
                _tagStyle.Draw(addRect, addContent, false, false, false, false);
                GUI.contentColor = previous;

                if (_draggingTag && _pressedTagIndex >= 0 && _pressedTagIndex < _tagRects.Count) {
                    if (_dropIndex >= 0) {
                        var marker = _dropIndex < _tagRects.Count
                            ? new Rect(_tagRects[_dropIndex].x - gap / 2f - 1.5f, _tagRects[_dropIndex].y, 3f, chipHeight)
                            : new Rect(_tagRects[_tagRects.Count - 1].xMax + gap / 2f - 1.5f,
                                _tagRects[_tagRects.Count - 1].y, 3f, chipHeight);
                        WorkflowStyles.DrawRect(marker, WorkflowStyles.AccentText, 1.5f);
                    }

                    var source = _tagRects[_pressedTagIndex];
                    var ghost = new Rect(e.mousePosition.x - source.width / 2f, e.mousePosition.y - chipHeight / 2f,
                        source.width, chipHeight);
                    DrawChip(ghost, contents[_pressedTagIndex], TagColour(_nameTags[_pressedTagIndex].Type), true,
                        true, 0.9f);
                }
            }

            // Tooltips (the chips themselves are drawn above)
            if (!_draggingTag)
                for (var i = 0; i < _tagRects.Count; i++)
                    GUI.Label(_tagRects[i], new GUIContent(string.Empty, contents[i].tooltip));

            if (GUI.Button(addRect, new GUIContent(string.Empty, addContent.tooltip), GUIStyle.none)) {
                _nameTags.Add(new NameTag { Type = TagType.Text });
                _selectedTagIndex = _nameTags.Count - 1;
                SaveNameTags();
                GUIUtility.ExitGUI();
            }
        }

        private void HandleTagMouse(Event e) {
            var id = GUIUtility.GetControlID(FocusType.Passive);

            switch (e.GetTypeForControl(id)) {
                case EventType.MouseDown when e.button == 0: {
                    var index = _tagRects.FindIndex(rect => rect.Contains(e.mousePosition));
                    if (index < 0) break;

                    _pressedTagIndex = index;
                    _dragStartMouse = e.mousePosition;
                    _draggingTag = false;
                    GUIUtility.hotControl = id;
                    GUI.FocusControl(null);
                    e.Use();

                    if (_selectedTagIndex != index) {
                        _selectedTagIndex = index;
                        GUIUtility.ExitGUI(); // the settings panel below changes
                    }

                    break;
                }
                case EventType.MouseDrag when GUIUtility.hotControl == id:
                    if (!_draggingTag && (e.mousePosition - _dragStartMouse).sqrMagnitude > 16f) _draggingTag = true;
                    if (_draggingTag) {
                        _dropIndex = DropIndexAt(e.mousePosition);
                        Repaint();
                    }

                    e.Use();
                    break;
                case EventType.MouseUp when GUIUtility.hotControl == id:
                    GUIUtility.hotControl = 0;
                    var moved = _draggingTag && _dropIndex >= 0;
                    if (moved) MoveTag(_pressedTagIndex, _dropIndex);

                    _draggingTag = false;
                    _pressedTagIndex = -1;
                    _dropIndex = -1;
                    e.Use();
                    Repaint();
                    if (moved) GUIUtility.ExitGUI();
                    break;
            }
        }

        // Where a dragged tag would land: the gap before the first tag (on the row under the mouse) whose middle is
        // to the right of the mouse, or the end of that row
        private int DropIndexAt(Vector2 mouse) {
            if (_tagRects.Count == 0) return 0;

            var rowY = _tagRects.Select(rect => rect.y).Distinct()
                .OrderBy(top => Mathf.Abs(top + 12f - mouse.y)).First();
            var lastInRow = -1;
            for (var i = 0; i < _tagRects.Count; i++) {
                if (!Mathf.Approximately(_tagRects[i].y, rowY)) continue;
                if (mouse.x < _tagRects[i].center.x) return i;
                lastInRow = i;
            }

            return lastInRow + 1;
        }

        /// <param name="from">The tag to move.</param>
        /// <param name="insertIndex">The gap to put it in (0 = before the first tag, Count = after the last).</param>
        private void MoveTag(int from, int insertIndex) {
            if (from < 0 || from >= _nameTags.Count) return;

            var tag = _nameTags[from];
            _nameTags.RemoveAt(from);
            if (insertIndex > from) insertIndex--;
            insertIndex = Mathf.Clamp(insertIndex, 0, _nameTags.Count);
            _nameTags.Insert(insertIndex, tag);
            _selectedTagIndex = insertIndex;
            SaveNameTags();
        }

        private void DrawChip(Rect rect, GUIContent content, Color colour, bool selected, bool hover, float alpha) {
            WorkflowStyles.DrawRect(rect, WithAlpha(colour, (selected ? 0.3f : hover ? 0.22f : 0.14f) * alpha), 12);
            WorkflowStyles.DrawRect(rect, WithAlpha(colour, (selected ? 1f : 0.55f) * alpha), 12, selected ? 2f : 1f);

            var previous = GUI.contentColor;
            GUI.contentColor = WithAlpha(colour, alpha);
            _tagStyle.Draw(rect, content, false, false, false, false);
            GUI.contentColor = previous;
        }

        // Settings for the selected tag
        private void DrawSelectedTag() {
            if (_selectedTagIndex < 0 || _selectedTagIndex >= _nameTags.Count) return;

            var tag = _nameTags[_selectedTagIndex];
            GUILayout.Space(8);
            _uiElements.BeginInset();

            EditorGUILayout.BeginHorizontal();
            GUILayout.Label(TagTypeName(tag.Type), EditorStyles.boldLabel, GUILayout.Height(24));
            GUILayout.FlexibleSpace();

            EditorGUI.BeginDisabledGroup(_selectedTagIndex == 0);
            var moveLeft = _uiElements.IconButton(WorkflowStyles.Icon("Animation.PrevKey"), "<",
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_MOVE_TAG_LEFT));
            EditorGUI.EndDisabledGroup();

            EditorGUI.BeginDisabledGroup(_selectedTagIndex >= _nameTags.Count - 1);
            var moveRight = _uiElements.IconButton(WorkflowStyles.Icon("Animation.NextKey"), ">",
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_MOVE_TAG_RIGHT));
            EditorGUI.EndDisabledGroup();

            // Only your own text tags can be removed; the others can be hidden with "Show in Name"
            var remove = tag.Type == TagType.Text && _uiElements.IconButton(WorkflowStyles.TrashIcon, "X",
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_REMOVE_TAG), true);
            EditorGUILayout.EndHorizontal();

            if (moveLeft || moveRight || remove) {
                if (moveLeft) MoveTag(_selectedTagIndex, _selectedTagIndex - 1);
                if (moveRight) MoveTag(_selectedTagIndex, _selectedTagIndex + 2);
                if (remove) {
                    _nameTags.RemoveAt(_selectedTagIndex);
                    _selectedTagIndex = -1;
                    SaveNameTags();
                }

                GUIUtility.ExitGUI();
            }

            EditorGUI.BeginChangeCheck();
            tag.Enabled = TooltipElements.Toggle(
                LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_TAG_SHOW), tag.Enabled,
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_TAG_SHOW));

            switch (tag.Type) {
                case TagType.GameName:
                    tag.Text = TooltipElements.TextField(
                        LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_TAG_NAME), tag.Text,
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_TAG_NAME));
                    break;
                case TagType.Stage:
                    tag.Option = TooltipElements.Popup(
                        LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_DEVELOPMENT_STAGE),
                        Mathf.Clamp(tag.Option, 0, _developmentStage.Length - 1), _developmentStage,
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_DEVELOPMENT_STAGE));
                    break;
                case TagType.Version:
                    tag.Text = TooltipElements.TextField(
                        LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_TAG_PREFIX), tag.Text,
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_TAG_PREFIX));
                    break;
                case TagType.Timestamp:
                    tag.Option = TooltipElements.Popup(
                        LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_TIMESTAMP_FORMAT),
                        Mathf.Clamp(tag.Option, 0, _timestampPresets.Length - 1), _timestampPresets,
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_TIMESTAMP_FORMAT));
                    break;
                default:
                    tag.Text = TooltipElements.TextField(
                        LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_TAG_TEXT), tag.Text,
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_TAG_TEXT));
                    break;
            }

            tag.Brackets = TooltipElements.Popup(
                LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_TAG_BRACKETS),
                Mathf.Clamp(tag.Brackets, 0, _brackets.Length - 1),
                new[] { LocalisationManager.Instance.GetString(LocalizationKeys.OPTION_NONE), "[ ]", "( )", "{ }" },
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_TAG_BRACKETS));
            if (EditorGUI.EndChangeCheck()) SaveNameTags();

            _uiElements.EndInset();
        }

        private void DrawNamePreview() {
            if (_previewStyle == null)
                _previewStyle = new GUIStyle(EditorStyles.wordWrappedLabel) { fontStyle = FontStyle.Bold };

            GUILayout.Space(6);
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_FILE_NAME_PREVIEW),
                WorkflowStyles.Caption);
            GUILayout.FlexibleSpace();
            var reset = _uiElements.IconButton(WorkflowStyles.ResetIcon, "R",
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_RESET_TAGS));
            EditorGUILayout.EndHorizontal();

            if (reset) {
                _nameTags = DefaultNameTags();
                _separatorIndex = 0;
                _selectedTagIndex = -1;
                SaveNameTags();
                SaveLoad.SaveInt(ToolName.POST_BUILD_ACTIONS, "NameSeparatorIndex", _separatorIndex);
                GUIUtility.ExitGUI();
            }

            _uiElements.BeginInset();
            GUILayout.Label(BuildBaseName() + ".zip", _previewStyle);
            _uiElements.EndInset();
        }

        private string ChipText(NameTag tag) {
            var part = TagPart(tag);
            return string.IsNullOrEmpty(part) ? TagTypeName(tag.Type) : part;
        }

        private static string TagTypeName(TagType type) {
            return LocalisationManager.Instance.GetString(type switch {
                TagType.GameName => LocalizationKeys.TAG_GAME_NAME,
                TagType.Stage => LocalizationKeys.TAG_STAGE,
                TagType.Version => LocalizationKeys.TAG_VERSION,
                TagType.Timestamp => LocalizationKeys.TAG_TIMESTAMP,
                _ => LocalizationKeys.TAG_TEXT
            });
        }

        private static Color TagColour(TagType type) {
            return type switch {
                TagType.GameName => WorkflowStyles.AccentText,
                TagType.Stage => WorkflowStyles.WarningText,
                TagType.Version => WorkflowStyles.InfoText,
                TagType.Timestamp => EditorGUIUtility.isProSkin
                    ? WorkflowStyles.Success
                    : (Color)new Color32(31, 122, 69, 255),
                _ => WorkflowStyles.Text
            };
        }

        private static Color WithAlpha(Color colour, float alpha) {
            return new Color(colour.r, colour.g, colour.b, colour.a * alpha);
        }

        private static Rect Offset(Rect rect, Vector2 by) {
            return new Rect(rect.x + by.x, rect.y + by.y, rect.width, rect.height);
        }

        #endregion

        #region Name Building

        private string TagValue(NameTag tag) {
            switch (tag.Type) {
                case TagType.GameName:
                    return string.IsNullOrWhiteSpace(tag.Text) ? Application.productName : tag.Text.Trim();
                case TagType.Stage:
                    return _developmentStage[Mathf.Clamp(tag.Option, 0, _developmentStage.Length - 1)];
                case TagType.Version:
                    return (tag.Text ?? string.Empty).Trim() + PlayerSettings.bundleVersion;
                case TagType.Timestamp:
                    return DateTime.Now.ToString(_timestampPresets[Mathf.Clamp(tag.Option, 0,
                        _timestampPresets.Length - 1)]);
                default:
                    return (tag.Text ?? string.Empty).Trim();
            }
        }

        // The tag's text with its brackets, or "" if the tag has nothing to show
        private string TagPart(NameTag tag) {
            var value = TagValue(tag);
            if (string.IsNullOrEmpty(value)) return string.Empty;

            var brackets = _brackets[Mathf.Clamp(tag.Brackets, 0, _brackets.Length - 1)];
            return brackets.Length == 2 ? brackets[0] + value + brackets[1] : value;
        }

        /// <summary>The zip name (without ".zip") from the shown tags, with characters Windows can't use removed.</summary>
        private string BuildBaseName() {
            var separator = _separators[Mathf.Clamp(_separatorIndex, 0, _separators.Length - 1)];
            var name = string.Join(separator,
                _nameTags.Where(tag => tag.Enabled).Select(TagPart).Where(part => part.Length > 0)).Trim();

            foreach (var invalid in Path.GetInvalidFileNameChars()) name = name.Replace(invalid.ToString(), "");
            return string.IsNullOrEmpty(name) ? "Build" : name;
        }

        private void LoadNameTags() {
            var json = SaveLoad.LoadString(ToolName.POST_BUILD_ACTIONS, "NameTags", string.Empty);
            if (!string.IsNullOrEmpty(json))
                try {
                    var saved = JsonUtility.FromJson<NameTagList>(json);
                    if (saved?.Tags != null && saved.Tags.Count > 0) {
                        _nameTags = saved.Tags;
                        return;
                    }
                }
                catch (ArgumentException) {
                    // Unreadable: fall through to the defaults
                }

            // First time with tags: start from the old "File Name Order" settings so names don't change
            _nameTags = DefaultNameTags(
                SaveLoad.LoadInt(ToolName.POST_BUILD_ACTIONS, "SelectedFileNameOrderIndex", 0),
                SaveLoad.LoadInt(ToolName.POST_BUILD_ACTIONS, "SelectedStageIndex", 0),
                SaveLoad.LoadInt(ToolName.POST_BUILD_ACTIONS, "SelectedTimestampIndex", 0),
                SaveLoad.LoadBoolean(ToolName.POST_BUILD_ACTIONS, "IncludeTimestamp"));
        }

        private void SaveNameTags() {
            SaveLoad.SaveString(ToolName.POST_BUILD_ACTIONS, "NameTags",
                JsonUtility.ToJson(new NameTagList { Tags = _nameTags }));
        }

        private static List<NameTag> DefaultNameTags(int order = 0, int stage = 0, int timestampFormat = 0,
            bool includeTimestamp = false) {
            var gameName = new NameTag { Type = TagType.GameName };
            var stageTag = new NameTag { Type = TagType.Stage, Brackets = 1, Option = stage };
            var version = new NameTag { Type = TagType.Version, Brackets = 2, Text = "v" };
            var timestamp = new NameTag {
                Type = TagType.Timestamp, Enabled = includeTimestamp, Option = timestampFormat
            };

            return order switch {
                1 => new List<NameTag> { gameName, version, stageTag, timestamp },
                2 => new List<NameTag> { timestamp, stageTag, gameName, version },
                _ => new List<NameTag> { gameName, stageTag, version, timestamp }
            };
        }

        #endregion

        private void DrawVersionUI() {
            _uiElements.GroupLabel(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_VERSION_NUMBER));
            GUILayout.Label(
                string.Format(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_CURRENT_VERSION),
                    PlayerSettings.bundleVersion), WorkflowStyles.Caption);

            _versionPartIndex = TooltipElements.Popup(
                LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_VERSION_PART),
                _versionPartIndex, _versionParts,
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_VERSION_PART));
            _bumpVersionOnBuild = TooltipElements.Toggle(
                LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_BUMP_VERSION_ON_BUILD),
                _bumpVersionOnBuild,
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_BUMP_VERSION_ON_BUILD));

            var nextVersion = BumpVersion(PlayerSettings.bundleVersion, _versionPartIndex);
            GUILayout.Space(4);
            EditorGUI.BeginDisabledGroup(nextVersion == null);
            if (_uiElements.SecondaryButton(new GUIContent(
                    string.Format(LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_BUMP_VERSION),
                        nextVersion ?? "-"),
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_BUMP_VERSION))))
                SetVersion(nextVersion);
            EditorGUI.EndDisabledGroup();
        }

        private void DrawBuildButton() {
            _uiElements.BeginSection(
                LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_BUILD),
                ref _showBuild,
                WorkflowStyles.BuildIcon
            );

            if (_showBuild) {
                var pathsMissing = string.IsNullOrEmpty(_buildsDir) || string.IsNullOrEmpty(_outputDir);
                if (pathsMissing)
                    _uiElements.Callout(
                        LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_ATTACH_BUILD_PATH), true);

                EditorGUI.BeginDisabledGroup(pathsMissing);
                if (_uiElements.PrimaryButton(
                        new GUIContent(
                            LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_EXECUTE_POST_BUILD_ACTIONS)),
                        38)) {
                    // Build after this GUI pass: building inside OnGUI breaks the window's layout
                    // ("EndLayoutGroup: BeginLayoutGroup must be called first")
                    EditorApplication.delayCall -= BuildGame;
                    EditorApplication.delayCall += BuildGame;
                }
                EditorGUI.EndDisabledGroup();
            }

            _uiElements.EndSection();
        }

        private void DrawPlayerSettingsUI() {
            _uiElements.BeginSubSection(
                LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_PLAYER),
                ref _showPlayerBuildSettings
            );

            if (_showPlayerBuildSettings) {
                _uiElements.GroupLabel(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_BUILD_OPTIONS));
                _buildDevelopment = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_SETTING_DEVELOPMENT_BUILD),
                    _buildDevelopment,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SETTING_DEVELOPMENT_BUILD));

                EditorGUI.BeginDisabledGroup(!_buildDevelopment);
                _buildAllowDebugging = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_SETTING_ALLOW_DEBUGGING),
                    _buildAllowDebugging,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SETTING_ALLOW_DEBUGGING));
                EditorGUI.EndDisabledGroup();

                _uiElements.GroupLabel(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_BUILD_SETTINGS));
                _buildCleanCache = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_SETTING_CLEAN_BUILD_CACHE),
                    _buildCleanCache,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SETTING_CLEAN_BUILD_CACHE));
                _buildStrictMode = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_SETTING_BUILD_STRICT_MODE),
                    _buildStrictMode,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SETTING_BUILD_STRICT_MODE));

                _uiElements.GroupLabel(LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_COMPRESSION));
                _buildCompressionIndex = TooltipElements.Popup(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_SETTING_BUILD_COMPRESSION_LEVEL),
                    _buildCompressionIndex, _buildCompressionValue,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SETTING_BUILD_COMPRESSION_LEVEL));
            }

            _uiElements.EndSubSection();
        }

        private void DrawFileSettingsUI() {
            _uiElements.BeginSubSection(
                LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_FILE),
                ref _showFileSettings,
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_BONUS_FILES_DESC)
            );

            if (_showFileSettings) {
                _addFiles = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_ADD_BONUS_FILES), _addFiles,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_ADD_BONUS_FILES));

                if (_addFiles) {
                    GUILayout.Space(4);

                    var removeIndex = -1;
                    for (var i = 0; i < _filePaths.Count; i++)
                        if (DrawFileEntry(i))
                            removeIndex = i;

                    if (_uiElements.SecondaryButton(new GUIContent(
                            " " + LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_ADD_FILE),
                            WorkflowStyles.PlusIcon,
                            LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_ADD_BONUS_FILES)))
                       ) {
                        AddNewFile();
                        GUIUtility.ExitGUI();
                    }

                    if (removeIndex >= 0) {
                        _filePaths.RemoveAt(removeIndex);
                        if (removeIndex < _destinationFolders.Count) _destinationFolders.RemoveAt(removeIndex);
                        GUIUtility.ExitGUI();
                    }
                }
            }

            _uiElements.EndSubSection();
        }

        private void DrawBuildSettingsUI() {
            _uiElements.BeginSubSection(
                LocalisationManager.Instance.GetString(LocalizationKeys.SECTION_TITLE_BUILD),
                ref _showBuildSettings,
                LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_BUILD_PLAYER)
            );

            if (_showBuildSettings) {
                _buildTarget[0] = string.Format(
                    LocalisationManager.Instance.GetString(LocalizationKeys.OPTION_CURRENT_PLATFORM),
                    PlatformName(EditorUserBuildSettings.activeBuildTarget));
                _buildTargetIndex = TooltipElements.Popup(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_SETTING_BUILD_TARGET),
                    Mathf.Clamp(_buildTargetIndex, 0, _buildTarget.Length - 1), _buildTarget,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SETTING_BUILD_TARGET));
                _zipCompressionIndex = TooltipElements.Popup(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_SETTING_ZIP_COMPRESSION),
                    _zipCompressionIndex, _zipCompressionAmount,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_SETTING_ZIP_COMPRESSION));
                _excludeDoNotShip = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_EXCLUDE_DO_NOT_SHIP),
                    _excludeDoNotShip,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_EXCLUDE_DO_NOT_SHIP));
                _createChecksum = TooltipElements.Toggle(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_CREATE_CHECKSUM),
                    _createChecksum,
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_CREATE_CHECKSUM));
            }

            _uiElements.EndSubSection();
        }

        /// <returns>True if the entry's remove button was clicked.</returns>
        private bool DrawFileEntry(int index) {
            if (index < 0 || index >= _filePaths.Count) return false;

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

            var fileName = Path.GetFileName(_filePaths[index]);
            GUILayout.Label(new GUIContent(fileName, _filePaths[index]), EditorStyles.boldLabel, GUILayout.Height(22),
                GUILayout.MinWidth(0));

            var removeClicked = _uiElements.IconButton(
                WorkflowStyles.TrashIcon,
                "X",
                LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_REMOVE_FILE),
                true
            );

            EditorGUILayout.EndHorizontal();

            if (index < _destinationFolders.Count)
                _destinationFolders[index] = TooltipElements.TextField(
                    LocalisationManager.Instance.GetString(LocalizationKeys.LABEL_DESTINATION_FOLDER),
                    _destinationFolders[index],
                    LocalisationManager.Instance.GetString(LocalizationKeys.TOOLTIP_DESTINATION_FOLDER));

            _uiElements.EndInset();
            return removeClicked;
        }

        #endregion

        #region Build Functions

        private string GetZipName() {
            var baseName = BuildBaseName();
            var zipFileName = baseName + ".zip";
            var counter = 1;

            while (File.Exists(Path.Combine(_outputDir, zipFileName))) zipFileName = $"{baseName} ({counter++}).zip";

            return zipFileName;
        }


        // Unity builds into this folder inside the build path, so the zip only ever holds what the build made.
        // It's deleted once the zip is safely in the export folder.
        private const string StagingFolderName = ".WorkflowToolkitBuild";

        private void BuildGame() {
            if (string.IsNullOrWhiteSpace(_buildsDir) || string.IsNullOrWhiteSpace(_outputDir)) {
                LoggingElements.LogError("Build or export path is not set. Please select both before building.");
                return;
            }

            if (!TryGetBuildTarget(out var target, out var group)) return;

            var scenes = EditorBuildSettings.scenes.Where(s => s.enabled).Select(s => s.path).ToArray();

            _buildOptions = new BuildOptionsBuilder()
                .SetDevelopment(_buildDevelopment)
                .AllowDebugging(_buildAllowDebugging)
                .CleanBuildCache(_buildCleanCache)
                .StrictMode(_buildStrictMode)
                .CompressionType(_buildCompressionIndex)
                .Build();

            // Bump first so the build itself carries the new version; put the old one back if the build fails
            var previousVersion = PlayerSettings.bundleVersion;
            var previousVersionCode = PlayerSettings.Android.bundleVersionCode;
            if (_bumpVersionOnBuild) {
                var nextVersion = BumpVersion(previousVersion, _versionPartIndex);
                if (nextVersion != null)
                    SetVersion(nextVersion);
                else
                    LoggingElements.LogWarning(
                        $"Couldn't bump the version \"{previousVersion}\" because it doesn't start with a number.");

                // Google Play only accepts an update if its version code is higher
                if (target == BuildTarget.Android) PlayerSettings.Android.bundleVersionCode = previousVersionCode + 1;
            }

            var stagingDir = Path.Combine(_buildsDir, StagingFolderName);
            DeleteFolder(stagingDir); // left over from a build that was interrupted
            Directory.CreateDirectory(stagingDir);

            // Android: always an .apk, even if "Build App Bundle" or "Export Project" is ticked in Build Settings
            var previousAppBundle = EditorUserBuildSettings.buildAppBundle;
            var previousExport = EditorUserBuildSettings.exportAsGoogleAndroidProject;
            if (target == BuildTarget.Android) {
                EditorUserBuildSettings.buildAppBundle = false;
                EditorUserBuildSettings.exportAsGoogleAndroidProject = false;
            }

            LoggingElements.LogInfo($"Building for {target} now, then moving to zipping.");
            BuildReport report;
            try {
                report = BuildPipeline.BuildPlayer(new BuildPlayerOptions {
                    scenes = scenes,
                    locationPathName = Path.Combine(stagingDir, PlayerFileName(target)),
                    target = target,
                    targetGroup = group,
                    options = _buildOptions
                });
            }
            finally {
                if (target == BuildTarget.Android) {
                    EditorUserBuildSettings.buildAppBundle = previousAppBundle;
                    EditorUserBuildSettings.exportAsGoogleAndroidProject = previousExport;
                }
            }

            if (report.summary.result != BuildResult.Succeeded) {
                if (PlayerSettings.bundleVersion != previousVersion) SetVersion(previousVersion);
                PlayerSettings.Android.bundleVersionCode = previousVersionCode;
                DeleteFolder(stagingDir);
                LoggingElements.LogError($"Build {report.summary.result}, so nothing was zipped.");
                Debug.LogError($"[Workflow Toolkit] Build {report.summary.result}, so nothing was zipped.");
                return;
            }

            var buildTime = report.summary.totalTime;
            Debug.Log($"[Workflow Toolkit] {target} build finished in {buildTime.Minutes}m {buildTime.Seconds}s.");

            if (!Directory.Exists(_outputDir)) {
                Directory.CreateDirectory(_outputDir);
                LoggingElements.LogInfo("Creating Directory Now:" + _outputDir);
            }

            if (_addFiles && _filePaths.Count > 0 && !CopyBonusFiles(stagingDir)) {
                DeleteFolder(stagingDir);
                return;
            }

            if (!ZipAndMove(stagingDir, Path.Combine(_buildsDir, GetZipName()))) {
                Debug.LogWarning($"[Workflow Toolkit] Zipping failed, so the build was left in {stagingDir}");
                return;
            }

            // Unity says to keep its do-not-ship folders (debug symbols, IL2CPP backups) for reading crash reports, so
            // when they were left out of the zip they're moved next to it. Everything else the build made is deleted.
            if (_excludeDoNotShip) KeepDoNotShipFolders(stagingDir, _buildsDir);
            DeleteFolder(stagingDir);
            LoggingElements.LogInfo("Zipped Requested Files...");
        }

        private bool TryGetBuildTarget(out BuildTarget target, out BuildTargetGroup group) {
            (target, group) = _buildTargetIndex switch {
                1 => (BuildTarget.StandaloneWindows64, BuildTargetGroup.Standalone),
                2 => (BuildTarget.StandaloneLinux64, BuildTargetGroup.Standalone),
                3 => (BuildTarget.Android, BuildTargetGroup.Android),
                4 => (BuildTarget.iOS, BuildTargetGroup.iOS),
                _ => (EditorUserBuildSettings.activeBuildTarget,
                    BuildPipeline.GetBuildTargetGroup(EditorUserBuildSettings.activeBuildTarget))
            };

            if (BuildPipeline.IsBuildTargetSupported(group, target)) return true;

            var message = $"{PlatformName(target)} build support " +
                          "isn't installed. Add it to this Unity version in the Unity Hub (Installs > Add modules).";
            LoggingElements.LogError(message);
            Debug.LogError("[Workflow Toolkit] " + message);
            return false;
        }

        private static string PlatformName(BuildTarget target) {
            return target switch {
                BuildTarget.StandaloneWindows or BuildTarget.StandaloneWindows64 => "Windows",
                BuildTarget.StandaloneLinux64 => "Linux",
                BuildTarget.StandaloneOSX => "macOS",
                BuildTarget.Android => "Android",
                BuildTarget.iOS => "iOS",
                BuildTarget.WebGL => "Web",
                _ => target.ToString()
            };
        }

        // What Unity is asked to build: a file for Windows, Linux and Android, an app for macOS, and a folder for
        // iOS (an Xcode project), the web and anything else
        private string PlayerFileName(BuildTarget target) {
            var name = string.Concat(_gameName.Split(Path.GetInvalidFileNameChars())).Trim();
            if (string.IsNullOrEmpty(name)) name = "Game";

            return target switch {
                BuildTarget.StandaloneWindows or BuildTarget.StandaloneWindows64 => name + ".exe",
                BuildTarget.StandaloneLinux64 => name + ".x86_64",
                BuildTarget.StandaloneOSX => name + ".app",
                BuildTarget.Android => name + ".apk",
                _ => name
            };
        }

        /// <returns>False if the bonus file lists don't match, in which case nothing should be zipped.</returns>
        private bool CopyBonusFiles(string stagingDir) {
            if (_filePaths.Count != _destinationFolders.Count) {
                LoggingElements.LogError(
                    "The # of filepaths doesn't match the number of destination folders. Ensure both lists are synchronized.");
                return false;
            }

            for (var i = 0; i < _filePaths.Count; i++) {
                var filePath = _filePaths[i];
                var targetFolderPath = Path.Combine(stagingDir, _destinationFolders[i] ?? string.Empty);
                var targetFilePath = Path.Combine(targetFolderPath, Path.GetFileName(filePath));

                // The original stays where it is; only this copy goes into the zip (and is deleted with the build)
                try {
                    Directory.CreateDirectory(targetFolderPath);
                    File.Copy(filePath, targetFilePath, true);
                    LoggingElements.LogInfo($"Copied {Path.GetFileName(filePath)} to {targetFolderPath}");
                }
                catch (Exception ex) {
                    LoggingElements.LogError(
                        $"Failed to copy {Path.GetFileName(filePath)} to {targetFolderPath}: {ex.Message}");
                }
            }

            return true;
        }

        /// <returns>True once the zip is in the export folder.</returns>
        private bool ZipAndMove(string sourceDir, string zipFilePath) {
            try {
                ZipDirectory(sourceDir, zipFilePath, _zipCompressionIndex, _excludeDoNotShip);

                var finalZipPath = Path.Combine(_outputDir, Path.GetFileName(zipFilePath));
                if (!string.Equals(Path.GetFullPath(zipFilePath), Path.GetFullPath(finalZipPath),
                        StringComparison.OrdinalIgnoreCase))
                    File.Move(zipFilePath, finalZipPath);

                if (_createChecksum) WriteChecksum(finalZipPath);
                return File.Exists(finalZipPath);
            }
            catch (Exception ex) {
                Debug.LogError(ex);
                LoggingElements.LogError(ex.ToString());
                return false;
            }
        }

        private static void KeepDoNotShipFolders(string stagingDir, string buildDir) {
            foreach (var folder in Directory.GetDirectories(stagingDir)) {
                var name = Path.GetFileName(folder);
                if (name.IndexOf("DoNotShip", StringComparison.OrdinalIgnoreCase) < 0 &&
                    name.IndexOf("DontShip", StringComparison.OrdinalIgnoreCase) < 0) continue;

                try {
                    var destination = Path.Combine(buildDir, name);
                    DeleteFolder(destination); // the previous build's copy
                    Directory.Move(folder, destination);
                }
                catch (Exception ex) {
                    LoggingElements.LogWarning($"Couldn't keep {name}: {ex.Message}");
                }
            }
        }

        // Deletes a folder the toolkit made, read-only files included
        private static void DeleteFolder(string path) {
            if (!Directory.Exists(path)) return;

            try {
                foreach (var file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
                    File.SetAttributes(file, FileAttributes.Normal);
                Directory.Delete(path, true);
            }
            catch (Exception ex) {
                LoggingElements.LogWarning($"Couldn't delete {path}: {ex.Message}");
            }
        }

        /// <returns>The files that went into the zip.</returns>
        private static List<string> ZipDirectory(string sourceDir, string zipFilePath, int compressionValue,
            bool leaveOutDoNotShip) {
            var files = new List<string>(Directory.GetFiles(sourceDir, "*", SearchOption.AllDirectories));
            files.RemoveAll(path =>
                (leaveOutDoNotShip && IsInDoNotShipFolder(sourceDir, path)) ||
                Path.GetExtension(path).Equals(".zip", StringComparison.OrdinalIgnoreCase));

            using var zipToOpen = new FileStream(zipFilePath, FileMode.Create);
            using var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create);

            foreach (var file in files) {
                // Zip entries always use "/", or the zip looks broken on macOS and Linux
                var entryName = file.Substring(sourceDir.Length + 1).Replace('\\', '/');
                var compressionLevel = compressionValue switch {
                    0 => CompressionLevel.NoCompression,
                    1 => CompressionLevel.Fastest,
                    2 => CompressionLevel.Optimal,
                    _ => CompressionLevel.Optimal
                };
                archive.CreateEntryFromFile(file, entryName, compressionLevel);
            }

            return files;
        }

        // Unity puts debug symbols and IL2CPP backups next to the build in folders such as
        // "<Game>_BurstDebugInformation_DoNotShip" and "<Game>_BackUpThisFolder_ButDontShipItWithYourGame"
        private static bool IsInDoNotShipFolder(string rootDir, string filePath) {
            var relativeFolders = Path.GetDirectoryName(filePath.Substring(rootDir.Length)
                .TrimStart(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
            if (string.IsNullOrEmpty(relativeFolders)) return false;

            return relativeFolders.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar).Any(folder =>
                folder.IndexOf("DoNotShip", StringComparison.OrdinalIgnoreCase) >= 0 ||
                folder.IndexOf("DontShip", StringComparison.OrdinalIgnoreCase) >= 0);
        }

        // Writes "<file>.sha256" as "<hash>  <file name>", the format sha256sum and most checksum tools read
        private static void WriteChecksum(string filePath) {
            try {
                string hash;
                using (var stream = File.OpenRead(filePath))
                using (var sha256 = SHA256.Create()) {
                    hash = BitConverter.ToString(sha256.ComputeHash(stream)).Replace("-", "").ToLowerInvariant();
                }

                File.WriteAllText(filePath + ".sha256", $"{hash}  {Path.GetFileName(filePath)}\n");
                LoggingElements.LogInfo($"Saved checksum {hash} to {Path.GetFileName(filePath)}.sha256");
            }
            catch (Exception ex) {
                LoggingElements.LogError($"Couldn't create the checksum file: {ex.Message}");
            }
        }

        /// <summary>
        ///     Works out the next version: "1.2.3" becomes "1.2.4" (Patch), "1.3.0" (Minor) or "2.0.0" (Major).
        ///     Missing parts count as 0, and text after the numbers (like "-beta") is kept.
        /// </summary>
        /// <returns>The new version, or null if the version doesn't start with a number.</returns>
        private static string BumpVersion(string version, int partIndex) {
            var match = Regex.Match(version ?? "", @"^(\d+)(?:\.(\d+))?(?:\.(\d+))?(.*)$");
            if (!match.Success) return null;

            if (!int.TryParse(match.Groups[1].Value, out var major)) return null;
            var minor = 0;
            var patch = 0;
            if (match.Groups[2].Success && !int.TryParse(match.Groups[2].Value, out minor)) return null;
            if (match.Groups[3].Success && !int.TryParse(match.Groups[3].Value, out patch)) return null;

            switch (partIndex) {
                case 0:
                    major++;
                    minor = 0;
                    patch = 0;
                    break;
                case 1:
                    minor++;
                    patch = 0;
                    break;
                default:
                    patch++;
                    break;
            }

            // Any extra number parts (a fourth ".7") go back to 0, like the parts below the one that went up
            var rest = Regex.Replace(match.Groups[4].Value, @"^(\.\d+)+", m => Regex.Replace(m.Value, @"\d+", "0"));
            return $"{major}.{minor}.{patch}{rest}";
        }

        private void SetVersion(string version) {
            if (string.IsNullOrEmpty(version)) return;

            PlayerSettings.bundleVersion = version;
            AssetDatabase.SaveAssets();
            LoggingElements.LogInfo($"Version is now {version}");
        }

        private void AddNewFile() {
            var path = EditorUtility.OpenFilePanel(
                LocalisationManager.Instance.GetString(LocalizationKeys.BUTTON_SELECT_FILE), "", "");
            if (string.IsNullOrEmpty(path)) return;

            _filePaths.Add(path);
            _destinationFolders.Add("");
        }

        #endregion
    }
}
#endif