﻿using AsmodeeDigital.Common.Plugin.Domain.Data;
using AsmodeeDigital.Common.Plugin.Editor;
using AsmodeeDigital.Common.Plugin.Manager.Event;
using AsmodeeDigital.Common.Plugin.Network;
using AsmodeeDigital.Common.Plugin.Utils;
using AsmodeeDigital.CrossPromo.Plugin.Domain;
using AsmodeeDigital.CrossPromo.Plugin.Domain.Data;
using AsmodeeDigital.CrossPromo.Plugin.Manager;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using UnityEditor;
using UnityEngine;

namespace AsmodeeDigital.CrossPromo.Plugin.Editor
{
    [InitializeOnLoad]
    public class CrossPromoMenu : ScriptableObject
    {
        public DoWNetworkParameters NetworkParameters;
        public bool DownloadImages = true;

        private static CrossPromoMenu _instance;

#if UNITY_ANDROID
            public static string BuildPath = "..\\Builds\\CrossPromo\\Android\\CrossPromo_Sample.apk";
#elif UNITY_IOS
            public static string BuildPath = "/Builds/CrossPromo/iOS/CrossPromo_Sample";
#elif UNITY_STANDALONE_WIN
        public static string BuildPath = "..\\Builds\\CrossPromo\\Windows\\CrossPromo_Sample.exe";
#elif UNITY_STANDALONE_OSX
            public static string BuildPath = "Builds/CrossPromo/OSX/CrossPromo_Sample.app";
#elif UNITY_STANDALONE_LINUX
            public static string BuildPath = "Builds/CrossPromo/Linux/CrossPromo_Sample";
#endif

        private static StateDownloadingCache State = StateDownloadingCache.NotStarted;

        static CrossPromoMenu()
        {
        }

        [MenuItem("CrossPromo/Download cache and build")]
        private static void DownloadCacheAndBuild()
        {
            DownloadCache();
            Build();
        }

        [MenuItem("CrossPromo/Download cache")]
        private static void DownloadCache()
        {
            try
            {
                //--- Delete previous cache
                string pathCache = Path.Combine(Application.dataPath, "Resources/AsmodeeDigital/CrossPromo/Cache");
                if (Directory.Exists(pathCache))
                    Directory.Delete(pathCache, true);
                //---

                //Tricks to get the NetworkParameters assigned to the script
                _instance = ScriptableObject.CreateInstance<CrossPromoMenu>();

                RestAPI restAPI = new RestAPI(_instance.NetworkParameters);
                EventManager.Instance = new Common.Plugin.Tests.Mocks.EventManagerTest();

                AuthenticationTokens authenticationTokens = null;
                MoreGamesFilters currentFilter = MoreGamesFilters.None;
                State = StateDownloadingCache.MoreGames;

                restAPI.ConnectionSuccessEvent += (AuthenticationTokens at) =>
                {
                    authenticationTokens = at;
                    DownloadNext(restAPI, authenticationTokens, ref currentFilter);
                };

                restAPI.ReceivingGroupProductEvent += (GroupProduct gp) =>
                {
                    CrossPromoCacheManager.SaveGroupProductInCache(gp, true);
                    DownloadNext(restAPI, authenticationTokens, ref currentFilter);
                };

                restAPI.ReceivingProductEvent += (Product p) =>
                {
                    CrossPromoCacheManager.SaveBannerInCache(p, true, true);

                    ChangeResourcesImagesParameters();
                };

                restAPI.Connect();
            }
            finally
            {
                EditorUtility.ClearProgressBar();
            }
        }

        private static void DownloadNext(RestAPI restAPI, AuthenticationTokens authenticationTokens, ref MoreGamesFilters currentFilter)
        {
            if (State == StateDownloadingCache.MoreGames && currentFilter < MoreGamesFilters.Board)
            {
                currentFilter++;
                //TODO : get cache for 3 and 4 columns
                restAPI.MoreGameRequest(authenticationTokens.access_token, currentFilter, 3);
            }
            else if (State == StateDownloadingCache.MoreGames)
            {
                State = StateDownloadingCache.Interstital;
                restAPI.InterstitialRequest(authenticationTokens.access_token, 3);
            }
            else if (State == StateDownloadingCache.Interstital)
            {
                State = StateDownloadingCache.Banner;
                restAPI.BannerRequest(authenticationTokens.access_token);
            }
        }


        private static void Build()
        {
            string codeBase = Assembly.GetExecutingAssembly().CodeBase;
            UriBuilder uri = new UriBuilder(codeBase);
            string path = Uri.UnescapeDataString(uri.Path);

            path = Path.Combine(Directory.GetParent(path).Parent.Parent.FullName, BuildPath);
            Directory.CreateDirectory(Path.GetDirectoryName(path));

            string[] levels = new string[] {
            "Assets/Samples/CrossPromo/Scenes/1_Banner.unity"};

#if UNITY_ANDROID
            BuildPipeline.BuildPlayer(levels, path, BuildTarget.Android, BuildOptions.None);
#elif UNITY_IOS
            BuildPipeline.BuildPlayer(levels, path, BuildTarget.iOS, BuildOptions.None);
#elif UNITY_STANDALONE_WIN
            BuildPipeline.BuildPlayer(levels, path, BuildTarget.StandaloneWindows, BuildOptions.None);
#elif UNITY_STANDALONE_OSX
            BuildPipeline.BuildPlayer(levels, path, BuildTarget.StandaloneOSXUniversal, BuildOptions.None);
#elif UNITY_STANDALONE_LINUX
            BuildPipeline.BuildPlayer(levels, path, BuildTarget.StandaloneLinuxUniversal, BuildOptions.None);
#endif
        }

        private static void ChangeResourcesImagesParameters()
        {
            UnityEditor.AssetDatabase.Refresh();

            string pathStaticCache = "Assets/Resources/AsmodeeDigital/CrossPromo/Cache/";
            string[] pathsImages = AssetDatabase.GetAllAssetPaths();

            float count = 0;
            foreach (string pathImage in pathsImages)
            {
                count++;
#if UNITY_EDITOR
                if (!Application.isPlaying)
                    EditorUtility.DisplayProgressBar("Downloading Cross Promo cache", "Updating images", count / (float)pathsImages.Length);
#endif
                if (pathImage.StartsWith(pathStaticCache) && pathImage.EndsWith(".png"))
                {
                    TextureImporter importer = AssetImporter.GetAtPath(pathImage) as TextureImporter;
                    importer.mipmapEnabled = false;
                    importer.SaveAndReimport();
                }
            }

            UnityEditor.AssetDatabase.SaveAssets();
            UnityEditor.AssetDatabase.Refresh();

            EditorUtility.ClearProgressBar();
        }

        public enum StateDownloadingCache : int
        {
            NotStarted = 0,
            MoreGames = 1,
            Interstital = 2,
            Banner = 3
        }
    }
}
