﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;

namespace LicenseSpring
{
    public class ExampleOfflineUIManager : MonoBehaviour
    {
        #region Declaration

        public LicenseSpringSDK SDKObject;

        [Header("UI elements")]

        #pragma warning disable 0649
        [SerializeField]
        private InputField userNameInput;
        #pragma warning restore 0649

        #pragma warning disable 0649
        [SerializeField]
        private InputField passwordInput;
        #pragma warning restore 0649

        #pragma warning disable 0649
        [SerializeField]
        private Button activateLicense;
        #pragma warning restore 0649

        #pragma warning disable 0649
        [SerializeField]
        private Button deactivateLicense;
        #pragma warning restore 0649

        #pragma warning disable 0649
        [SerializeField]
        private Button loadLicenseFile;
        #pragma warning restore 0649


        #pragma warning disable 0649
        private string licenseLocalFileURL;
        #pragma warning restore 0649

        #endregion

        private void Awake()
        {
            InitializeUI();
        }
        
        private void InitializeUI()
        {
            loadLicenseFile.onClick.AddListener(ActivateLiceseFromFile);
            activateLicense.onClick.AddListener(ActivateLicenseKey);
            deactivateLicense.onClick.AddListener(DeactivateLicenseKey);

            //check sdkErrors
            LicenseSpringSDK.sdkException += SDKErrors;
        }

        private void ActivateLiceseFromFile()
        {
            #if UNITY_EDITOR
            string path = EditorUtility.OpenFilePanel("License file", "", "");
            
            if (path.Length != 0)
            {
                SDKObject.ActivateLicenseOffline(path);
            }
            #endif
        }

        private void ActivateLicenseKey()
        {
            LicenseStatus license = new LicenseStatus();
            SDKObject.ActivateLicense(userNameInput.text, passwordInput.text);

            if (license.IsActive())
            {
                Debug.Log("License Online Activate - complited!");
            }
            else
            {
                Debug.Log(license.ToString());
            }
        }

        private void DeactivateLicenseKey()
        {
            if (SDKObject.DeactivateCurrentLicenseOnline())
            {
                Debug.Log("License Deactivate Online - complited!");
            }
            else
            {
                Debug.Log("The license was deactivated earlier!");
            }
        }

        private void SDKErrors(Exception sdkException)
        {
            Debug.LogError("SDK Exception: " + sdkException.Message);
        }
    }
}
