﻿using System;
using UnityEngine;
using UnityEngine.UI;

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

        public LicenseSpringSDK SDKObject;

        [Header("UI elements")]
        [SerializeField]
        private Button getLicense = null;

        [SerializeField]
        private Button getCurrentLicense = null;

        [SerializeField]
        private Button checkLicense = null;

        [SerializeField]
        private Button saveLicense = null;

        [SerializeField]
        private Button activateLicense = null;

        [SerializeField]
        private Button deactivateLicense = null;
        
        [SerializeField]
        private InputField licenseKey = null;

        [SerializeField]
        private Text licenseStatus = null;

        [SerializeField]
        private Text licenseURL = null;

        #endregion

        private void Awake()
        {
            InitializeUI();
        }

        private void InitializeUI()
        {
            getLicense.onClick.AddListener(GetLicenseKey);
            getCurrentLicense.onClick.AddListener(GetCurrentLicenseKey);
            checkLicense.onClick.AddListener(CheckLicenseStatus);
            saveLicense.onClick.AddListener(SaveLiceneseFile);
            activateLicense.onClick.AddListener(ActivateLicenseKey);
            deactivateLicense.onClick.AddListener(DeactivateLicenseKey);

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

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

        private void GetLicenseKey()
        {
            licenseKey.text = SDKObject.GetTrialLicense();
        }

        private void GetCurrentLicenseKey()
        {
            licenseKey.text = SDKObject.license.Key();
        }

        private void CheckLicenseStatus()
        {
            licenseStatus.text = SDKObject.CheckLicense(licenseKey.text) + SDKObject.GetAllLicenseInfo() + "\n Days remeaning: " + SDKObject.DaysPasset();
        }

        private void SaveLiceneseFile()
        {
            licenseURL.text = SDKObject.GetActivationFile(licenseKey.text);
        }

        private void ActivateLicenseKey()
        {
            SDKObject.ActivateLicense(licenseKey.text);

            LicenseStatus license = new LicenseStatus();

            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!");
            }
        }
    }
}