﻿using UnityEditor;
using UnityEngine;
using UnityEditorInternal;
using System.Collections.Generic;
using System.Linq;

namespace Adverty5.Editor
{
    internal class SettingsWindow : AdvertyWindow
    {
        private const string PLATORM_SETTING_TITLE = "API-Key Setup";
        private const string SANDBOX_MODE_LABEL = "Sandbox Mode";
        private const string SETTINGS_TITLE = "Settings";
        private const string API_KEY_WARNING = "Invalid API key";
        private const string PLATFORM_LIST_VARIABLE_NAME = "platformSettings";
        protected const int SPACE_INTERVAL = 5;

        protected SerializedObject serializedObject;
        private SerializedProperty serializedProperty;
        private ReorderableList settingsList;
        private List<string> platformNames = new List<string> { "Android", "iOS", "Other" };

        [MenuItem(SETTINGS_MENU_ITEM_PATH, false, MENU_QUEUE_VALUE)]
        public static void ShowWindow()
        {
            EditorWindow window = GetWindow(typeof(SettingsWindow));
            window.minSize = new Vector2(900, 400);
            window.maxSize = new Vector2(900, 400);
        }

        private void OnEnable()
        {
            titleContent.text = SETTINGS_TITLE;

            serializedObject = new SerializedObject(AdvertySettings.Instance);
            serializedProperty = serializedObject.FindProperty(PLATFORM_LIST_VARIABLE_NAME);
            settingsList = new ReorderableList(serializedObject, serializedProperty, false, true, true, true) {
                drawHeaderCallback = ReorderableListDrawHeader, drawElementCallback = ReorderableListDrawElement,
                elementHeightCallback = ReorderableListElementHeight, onAddDropdownCallback = ReorderableListAddElement,
                drawNoneElementCallback = ReorderableListNoElement
            };
        }

        private void ReorderableListNoElement(Rect rect)
        {
            EditorGUI.LabelField(rect, "No API Key added", EditorStyles.label);
        }

        private void ReorderableListAddElement(Rect buttonRect, ReorderableList list)
        {
            GenericMenu menu = new GenericMenu();

            foreach (int platform in (int[])System.Enum.GetValues(typeof(SupportedPlatform)))
            {
                if (!AdvertySettings.Instance.platformSettings.Any(
                        platformSetting =>
                        { return (int)platformSetting.platform == platform; }))
                {
                    menu.AddItem(new GUIContent(System.Enum.GetName(typeof(SupportedPlatform), platform)), false,
                                 OnDropDownItemClicked, platform);
                }
            }

            menu.ShowAsContext();
        }

        private void OnDropDownItemClicked(object target)
        {
            int selectedPlatform = (int)target;

            settingsList.serializedProperty.arraySize++;
            settingsList.index = settingsList.serializedProperty.arraySize - 1;
            SerializedProperty element = settingsList.serializedProperty.GetArrayElementAtIndex(settingsList.index);
            element.FindPropertyRelative("platform").enumValueIndex = selectedPlatform;
            element.FindPropertyRelative("apiKey").stringValue = string.Empty;
            serializedObject.ApplyModifiedProperties();
        }

        private float ReorderableListElementHeight(int index)
        {
            if (index < 0)
            {
                return EditorGUIUtility.singleLineHeight;
            }

            SerializedProperty platformSettingElement = serializedProperty.GetArrayElementAtIndex(index);
            SerializedProperty apiKeyProperty = platformSettingElement.FindPropertyRelative("apiKey");

            if (IsAPIKeyValid(apiKeyProperty.stringValue))
            {
                return EditorGUIUtility.singleLineHeight * 2.5f;
            }

            return EditorGUIUtility.singleLineHeight * 5f;
        }

        private void ReorderableListDrawElement(Rect rect, int index, bool isActive, bool isFocused)
        {
            SerializedProperty platformSettingElement = serializedProperty.GetArrayElementAtIndex(index);

            SerializedProperty platformProperty = platformSettingElement.FindPropertyRelative("platform");
            EditorGUI.LabelField(new Rect(rect.x, rect.y + EditorGUIUtility.singleLineHeight * 0.1f, rect.width,
                                          EditorGUIUtility.singleLineHeight),
                                 platformNames[platformProperty.enumValueIndex], EditorStyles.boldLabel);
            SerializedProperty apiKeyProperty = platformSettingElement.FindPropertyRelative("apiKey");
            EditorGUI.PropertyField(new Rect(rect.x, rect.y + EditorGUIUtility.singleLineHeight * 1.25f, rect.width,
                                             EditorGUIUtility.singleLineHeight),
                                    apiKeyProperty);

            if (!IsAPIKeyValid(apiKeyProperty.stringValue))
            {
                EditorGUI.HelpBox(new Rect(rect.x, rect.y + EditorGUIUtility.singleLineHeight * 2.75f, rect.width,
                                           EditorGUIUtility.singleLineHeight * 2f),
                                  API_KEY_WARNING, MessageType.Warning);
            }
        }

        private void ReorderableListDrawHeader(Rect rect)
        {
            EditorGUI.LabelField(rect, PLATORM_SETTING_TITLE, EditorStyles.label);
        }

        protected virtual void OnGUI()
        {
            GUILayout.Space(SPACE_INTERVAL * 3);

            serializedObject.Update();

            settingsList.DoLayoutList();

            settingsList.displayAdd = settingsList.count < System.Enum.GetValues(typeof(SupportedPlatform)).Length;

            GUILayout.Space(SPACE_INTERVAL);

            GUIContent sandboxModeContent = new GUIContent(SANDBOX_MODE_LABEL);
            AdvertySettings.SandboxMode = EditorGUILayout.Toggle(sandboxModeContent, AdvertySettings.SandboxMode);

            serializedObject.ApplyModifiedProperties();

            EditorUtility.SetDirty(AdvertySettings.Instance);
        }

        private static bool IsAPIKeyValid(string key)
        {
            return !string.IsNullOrEmpty(key);
        }
    }
}
