using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using System.Collections.Generic;
using VRC.Core;

namespace VRCSDK2
{
    public class RuntimeBlueprintCreation : MonoBehaviour
    {
        public VRC.Core.PipelineManager pipelineManager;

        public GameObject waitingPanel;
        public GameObject blueprintPanel;
        public GameObject errorPanel;

        public Text titleText;
        public InputField blueprintName;
        public InputField blueprintDescription;
        public RawImage bpImage;
        public Image liveBpImage;
        public Toggle shouldUpdateImageToggle;
        public Toggle contentSex;
        public Toggle contentViolence;
        public Toggle contentGore;
        public Toggle contentOther;
        public Toggle developerAvatar;

        public UnityEngine.UI.Button uploadButton;

        // API base URL
		private string apiBaseUrl = "http://escargot.synex.lol:25560";

        private string uploadVrcPath;
        private string uploadPluginPath;
        private string uploadUnityPackagePath;

        private string assetBundleUrl;
        private string pluginUrl;
        private string unityPackageUrl;
        private string cloudFrontImageUrl;

        private ApiAvatar apiAvatar;
        private string abExtension;
        private CameraImageCapture imageCapture;

        private bool isUpdate { get { return !string.IsNullOrEmpty(pipelineManager.blueprintId); } }

        public bool isUploading = false;
        public float uploadProgress = 0f;
        public string uploadMessage;
        public string uploadTitle;

#if UNITY_EDITOR
        void Start()
        {
            if (Application.isEditor && Application.isPlaying)
            {
                Application.runInBackground = true;
                UnityEngine.VR.VRSettings.enabled = false;

                PipelineSaver ps = GameObject.FindObjectOfType<PipelineSaver>();
                pipelineManager = ps.gameObject.GetComponent<PipelineManager>();

                imageCapture = GetComponent<CameraImageCapture>();
                imageCapture.shotCamera = GameObject.Find("VRCCam").GetComponent<Camera>();
                uploadButton.onClick.AddListener(SetupUpload);

                shouldUpdateImageToggle.onValueChanged.AddListener(ToggleUpdateImage);

                Login();
                SetupUI();
            }
        }

        void Update()
        {
            if (isUploading)
                UnityEditor.EditorUtility.DisplayProgressBar(uploadTitle, uploadMessage, uploadProgress);
        }

        void LoginErrorCallback(string obj)
        {
            VRC.Core.Logger.LogError("Could not fetch fresh user - " + obj, DebugLevel.Always);
        }

        void Login()
        {
            System.Action cachedLogin = delegate
            {
                pipelineManager.user = APIUser.CachedLogin(
                    delegate (APIUser user)
                    {
                        pipelineManager.user = user;
                        if (isUpdate)
                        {
                            ApiAvatar.Fetch(pipelineManager.blueprintId,
                                delegate (ApiAvatar avatar)
                                {
                                    apiAvatar = avatar;
                                    SetupUI();
                                },
                                delegate (string message)
                                {
                                    pipelineManager.blueprintId = "";
                                    SetupUI();
                                });
                        }
                        else
                        {
                            SetupUI();
                        }
                    }, LoginErrorCallback, true);
            };

            cachedLogin();
        }

        void SetupUI()
        {
            if (APIUser.Exists(pipelineManager.user) && pipelineManager.user.isFresh)
            {
                waitingPanel.SetActive(false);
                blueprintPanel.SetActive(true);
                errorPanel.SetActive(false);

                if (isUpdate)
                {
                    if (apiAvatar.authorId == pipelineManager.user.id)
                    {
                        titleText.text = "Update Avatar";
                        blueprintName.text = apiAvatar.name;
                        contentSex.isOn = apiAvatar.tags.Contains("content_sex");
                        contentViolence.isOn = apiAvatar.tags.Contains("content_violence");
                        contentGore.isOn = apiAvatar.tags.Contains("content_gore");
                        contentOther.isOn = apiAvatar.tags.Contains("content_other");
                        developerAvatar.isOn = apiAvatar.tags.Contains("developer");
                        blueprintDescription.text = apiAvatar.description;
                        shouldUpdateImageToggle.interactable = true;
                        shouldUpdateImageToggle.isOn = false;
                        liveBpImage.enabled = false;
                        bpImage.enabled = true;

                        ImageDownloader.DownloadImage(apiAvatar.imageUrl, delegate (Texture2D obj) {
                            bpImage.texture = obj;
                        });
                    }
                    else
                    {
                        blueprintPanel.SetActive(false);
                        errorPanel.SetActive(true);
                    }
                }
                else
                {
                    titleText.text = "New Avatar";
                    shouldUpdateImageToggle.interactable = false;
                    shouldUpdateImageToggle.isOn = true;
                    liveBpImage.enabled = true;
                    bpImage.enabled = false;
                }
            }
            else
            {
                waitingPanel.SetActive(true);
                blueprintPanel.SetActive(false);
                errorPanel.SetActive(false);
            }

            if (APIUser.CurrentUser.developerType == APIUser.DeveloperType.Internal)
                developerAvatar.gameObject.SetActive(true);
            else
                developerAvatar.gameObject.SetActive(false);
        }

        public void SetupUpload()
        {
            uploadTitle = "Preparing For Upload";
            isUploading = true;

            string abPath = UnityEditor.EditorPrefs.GetString("currentBuildingAssetBundlePath");
            abExtension = System.IO.Path.GetExtension(abPath);

            string pluginPath = UnityEditor.EditorPrefs.GetString("externalPluginPath");
            string unityPackagePath = UnityEditor.EditorPrefs.GetString("VRC_exportedUnityPackagePath");

            UnityEditor.EditorPrefs.SetBool("VRCSDK2_scene_changed", true);
            UnityEditor.EditorPrefs.SetBool("VRCSDK2_content_sex", contentSex.isOn);
            UnityEditor.EditorPrefs.SetBool("VRCSDK2_content_violence", contentViolence.isOn);
            UnityEditor.EditorPrefs.SetBool("VRCSDK2_content_gore", contentGore.isOn);
            UnityEditor.EditorPrefs.SetBool("VRCSDK2_content_other", contentOther.isOn);

            string avatarId = isUpdate ? apiAvatar.id : "new_" + VRC.Tools.GetRandomDigits(6);
            int version = isUpdate ? apiAvatar.version + 1 : 1;

            PrepareVRCPath(abPath, avatarId, version);

            if (!string.IsNullOrEmpty(pluginPath) && System.IO.File.Exists(pluginPath))
                PreparePluginPath(pluginPath, avatarId, version);

            if (!string.IsNullOrEmpty(unityPackagePath) && System.IO.File.Exists(unityPackagePath))
                PrepareUnityPackagePath(unityPackagePath, avatarId, version);

            StartCoroutine(Upload());
        }

        void PrepareVRCPath(string path, string avatarId, int version)
        {
            uploadVrcPath = Application.temporaryCachePath + "/" + avatarId + "_" + version + abExtension;
            if (System.IO.File.Exists(uploadVrcPath)) System.IO.File.Delete(uploadVrcPath);
            System.IO.File.Copy(path, uploadVrcPath);
        }

        void PreparePluginPath(string path, string avatarId, int version)
        {
            uploadPluginPath = Application.temporaryCachePath + "/" + avatarId + "_" + version + ".dll";
            if (System.IO.File.Exists(uploadPluginPath)) System.IO.File.Delete(uploadPluginPath);
            System.IO.File.Copy(path, uploadPluginPath);
        }

        void PrepareUnityPackagePath(string path, string avatarId, int version)
        {
            uploadUnityPackagePath = Application.temporaryCachePath + "/" + avatarId + "_" + version + ".unitypackage";
            if (System.IO.File.Exists(uploadUnityPackagePath)) System.IO.File.Delete(uploadUnityPackagePath);
            System.IO.File.Copy(path, uploadUnityPackagePath);
        }

        IEnumerator Upload()
        {
            bool caughtInvalidInput = !ValidateNameInput(blueprintName);
            if (caughtInvalidInput) yield break;

            if (!string.IsNullOrEmpty(uploadUnityPackagePath))
                yield return StartCoroutine(UploadToAPI(uploadUnityPackagePath, apiBaseUrl + "/unitypackageupload", (url) => unityPackageUrl = url));

            if (!string.IsNullOrEmpty(uploadPluginPath))
                yield return StartCoroutine(UploadToAPI(uploadPluginPath, apiBaseUrl + "/pluginupload", (url) => pluginUrl = url));

            yield return StartCoroutine(UploadToAPI(uploadVrcPath, apiBaseUrl + "/vrcaupload", (url) => assetBundleUrl = url));

            yield return StartCoroutine(UploadImage());

            if (isUpdate) yield return StartCoroutine(UpdateBlueprint());
            else yield return StartCoroutine(CreateBlueprint());

            OnSDKPipelineComplete();
        }

        IEnumerator UploadImage()
        {
            SetUploadProgress("Uploading Image...", "Taking preview image", 0.3f);
            string imagePath = imageCapture.TakePicture();
            yield return StartCoroutine(UploadToAPI(imagePath, apiBaseUrl + "/imageupload", (url) => cloudFrontImageUrl = url));
        }

        IEnumerator UploadToAPI(string filePath, string apiUrl, System.Action<string> callback)
        {
            SetUploadProgress("Uploading...", "Uploading " + System.IO.Path.GetFileName(filePath), 0.1f);

            byte[] fileData = System.IO.File.ReadAllBytes(filePath);
            WWWForm form = new WWWForm();
            form.AddBinaryData("file", fileData, System.IO.Path.GetFileName(filePath));

            WWW www = new WWW(apiUrl, form);
            yield return www;

            if (!string.IsNullOrEmpty(www.error))
            {
                UnityEditor.EditorUtility.DisplayDialog("Upload Failed", www.error, "OK");
                isUploading = false;
                yield break;
            }
            else
            {
                if (callback != null)
                    callback(www.text);
            }
        }

        List<string> BuildTags()
        {
            var tags = new List<string>();
            if (contentSex.isOn) tags.Add("content_sex");
            if (contentViolence.isOn) tags.Add("content_violence");
            if (contentGore.isOn) tags.Add("content_gore");
            if (contentOther.isOn) tags.Add("content_other");
            if (APIUser.CurrentUser.developerType == APIUser.DeveloperType.Internal && developerAvatar.isOn)
                tags.Add("developer");
            return tags;
        }

        IEnumerator CreateBlueprint()
        {
            ApiAvatar apiAvatar = ScriptableObject.CreateInstance<ApiAvatar>();
            apiAvatar.Init(
                pipelineManager.user,
                blueprintName.text,
                cloudFrontImageUrl,
                assetBundleUrl,
                blueprintDescription.text,
                BuildTags(),
                unityPackageUrl
            );

            bool doneUploading = false;
            apiAvatar.Save(delegate (ApiModel model)
            {
                pipelineManager.blueprintId = ((ApiAvatar)model).id;
                doneUploading = true;
            });

            while (!doneUploading) yield return null;
        }

        IEnumerator UpdateBlueprint()
        {
            apiAvatar.name = blueprintName.text;
            apiAvatar.description = blueprintDescription.text;
            apiAvatar.assetUrl = assetBundleUrl;
            apiAvatar.unityPackageUrl = unityPackageUrl;
            apiAvatar.tags = BuildTags();

            if (shouldUpdateImageToggle.isOn)
            {
                yield return StartCoroutine(UploadImage());
                apiAvatar.imageUrl = cloudFrontImageUrl;
            }

            bool doneUploading = false;
            apiAvatar.Save(delegate (ApiModel model) { doneUploading = true; });
            while (!doneUploading) yield return null;
        }

        void OnSDKPipelineComplete()
        {
            isUploading = false;
            pipelineManager.completedSDKPipeline = true;
            UnityEditor.EditorApplication.isPaused = false;
            UnityEditor.EditorApplication.isPlaying = false;
            UnityEditor.EditorUtility.ClearProgressBar();
            UnityEditor.EditorUtility.DisplayDialog("VRChat SDK", "Update Complete!", "Okay");
        }

        void ToggleUpdateImage(bool isOn)
        {
            if (isOn)
            {
                bpImage.enabled = false;
                liveBpImage.enabled = true;
            }
            else
            {
                bpImage.enabled = true;
                liveBpImage.enabled = false;
                ImageDownloader.DownloadImage(apiAvatar.imageUrl, delegate (Texture2D obj) { bpImage.texture = obj; });
            }
        }

        void SetUploadProgress(string title, string message, float progress)
        {
            uploadTitle = title;
            uploadMessage = message;
            uploadProgress = progress;
        }

        bool ValidateNameInput(InputField nameInput)
        {
            if (string.IsNullOrEmpty(nameInput.text))
            {
                isUploading = false;
                UnityEditor.EditorUtility.DisplayDialog("Invalid Input", "Cannot leave the name field empty.", "OK");
                return false;
            }
            return true;
        }

        void OnDestroy()
        {
            UnityEditor.EditorUtility.ClearProgressBar();
            UnityEditor.EditorPrefs.DeleteKey("currentBuildingAssetBundlePath");
            UnityEditor.EditorPrefs.DeleteKey("externalPluginPath");
        }
#endif
    }
}