﻿using System;
using System.Collections.Generic;
using System.Linq;
using ARGOFoundation;
using JetBrains.Annotations;
using UnityEditor;
using UnityEngine;

namespace ARGOEditor
{
    public class Deployer : Builder
    {
        [NotNull] private readonly Requester requester;
        private ProgressWindow progressWindow;

        internal Deployer() : base()
        {
            requester = Bootstrapper.Instance.Requester;
        }
        
        public void Deploy(List<BuildTarget> targets, int markerId)
        {
            if (progressWindow == null)
            {
                progressWindow = (ProgressWindow)EditorWindow.GetWindow(typeof(ProgressWindow), true, "Progress");
                progressWindow.minSize = new Vector2(215f, 100);
            }
            
            progressWindow.Show();

            requester.StartPostRequest
            (
                $"assets?page_id={markerId}&asset_type=16",
                GetFormsData(targets),
                true,
                OnComplete,
                OnError
            );
        }

        /// <exception cref="ArgumentException">Thrown on attempt to use not supported architecture</exception>
        private static string GetFormName(BuildTarget target)
        {
            var supportedArchitectures = new Dictionary<BuildTarget, string>()
            {
                {BuildTarget.iOS, "file"},
                {BuildTarget.Android, "file_android"}
            };
            try
            {
                return supportedArchitectures[target];
            }
            catch (KeyNotFoundException)
            {
                throw new ArgumentException
                (
                    $"Attempt to use not supported architecture ({target}), only { string.Join(",", supportedArchitectures.Keys) } are available",
                    nameof(target)
                );
            }
        }

        private FileFormData[] GetFormsData(IEnumerable<BuildTarget> targets)
        {
            return targets
                .Select(target => new FileFormData
                {
                    paramName = GetFormName(target),
                    fileName = BundleName,
                    filePath = $"{Paths[target]}{BundleName}"
                })
                .ToArray();
        }

        private void OnComplete(string json)
        {
            Debug.Log($"Success: {json}");
            progressWindow.Close();
            EditorUtility.DisplayDialog("Upload completed successfully", "", "OK");
        }

        private void OnError(string str)
        {
            Debug.Log($"Error occured: {str}");
            progressWindow.Close();
            EditorUtility.DisplayDialog("Error occurred", str, "OK");
        }
    }
}
