﻿using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;

using Augumenta;

/**
 * Script to initialize the Augumenta AIP.
 *
 * To use the Augumenta AIP this script must be loaded before using
 * any Augumenta AIP feature.
 *
 * NOTE: Augumenta initialization must be done before any registration,
 * otherwise the registrations done before initialization will fail.
 * Because of that, this script MUST be executed before any script that
 * might do any registrations. To ensure that this happens, set this script
 * as first in the 'Project Settings -> Script Execution Order'.
 *
 */

public class AugumentaInit : MonoBehaviour
{

	private const string LICENSE_RESOURCE_NAME = "License";

	/**
	 * Panel description to use for detecting X001.
	 */
	[System.Serializable]
	public class PanelSettings
	{
		[Tooltip("Panel format string for X001")]
		public string Format;
		[Tooltip("Panel payload string of the first payload for X001")]
		public string StartingPayload;
		[Tooltip("No of panels after payload_start for X001")]
		public int NoOfPanels;
	}
	public PanelSettings[] panels;
	/**
	 * Marker description to use for detecting X002.
	 */
	[Tooltip("Enable Default Marker detection for X002")]
	public bool defaultMarkerDetection = false;
	[Tooltip("Marker format string for X002")]
	public string[] markerFormats;
	[Tooltip("If enabled, the application will quit on back button pressed")]
	public bool QuitOnBackPressed = true;

	void Awake()
	{
		try {
			// try initialize Augumenta library with the license key
			if(!UnityAgapi.Init()) {
				Debug.LogError("Failed to get Augumenta AIP license validation");
				return;
			}
		} catch(InvalidOperationException e) {
			Debug.LogError("Failed to initialize Augumenta AIP");
			Debug.LogException(e);

			// show a Toast message
			showToast(e.Message);
			return;
		}

		UnityAgapi agapi = UnityAgapi.Instance;
		Debug.Log("Version: " + agapi.Version);

		if(panels.Length>0) {
			Debug.Log("We have " + panels.Length + " panel(s)");
			foreach(PanelSettings panel in panels) {
				Debug.Log("Adding panel: " + panel.Format + " " + panel.StartingPayload + " # " + panel.NoOfPanels);
				if(!agapi.AddPanelSet(Augumenta.Pose.X001, panel.Format, panel.StartingPayload, panel.NoOfPanels)) {
					Debug.LogError("Failed to add panel " + panel.Format +
								   " with payload: " + panel.StartingPayload +
								   " and " + panel.NoOfPanels +
								   " # of panels for detection");
				}
			}
		}

		if(defaultMarkerDetection) {
			Debug.Log("We have defaultMarkerDetection enabled");
			if(!agapi.AddDefaultMarkerFormat()) {
				Debug.LogError("Failed to add default marker!");
			}
		}

		if(markerFormats.Length>0) {
			Debug.Log("We have " + markerFormats.Length + " markers(s)");
			foreach(string markerFormat in markerFormats) {
				if(!agapi.AddMarkerFormat(markerFormat)) {
					Debug.LogError("Failed to add marker " + markerFormats +
								   " for detection");
				}
			}
		}
	}

	void Update()
	{
		//Check input for the first time
		if(QuitOnBackPressed && Input.GetKeyDown(KeyCode.Escape)) {
			Debug.Log("Back Button pressed in AugumentaInit. Quitting...");
			Application.Quit();
		}
	}

	/**
	 * Read license string from the Xml resource file.
	 *
	 * @param name Name of the resource
	 * @return License string
	 */
	private string readLicenseFromResources(string name)
	{
		string ret = UnityAgapi.GetLicenseFromResources(name);
		if(ret==null) {
			Debug.LogError("Invalid License.xml content");
		}
		return ret;
	}

	/**
	 * Show a Toast message.
	 *
	 * On Android it uses the Androids own Toast.
	 * Other platforms only show a debug log message.
	 *
	 * @param message Message string to show.
	 */
	private void showToast(string message)
	{
#if UNITY_ANDROID
		// Show license response message as toast on Android
		AndroidJavaClass unityPlayer = new AndroidJavaClass("com.unity3d.player.UnityPlayer");
		AndroidJavaObject activity = unityPlayer.GetStatic<AndroidJavaObject>("currentActivity");
		activity.Call("runOnUiThread", new AndroidJavaRunnable(() => {
			AndroidJavaClass toastClass = new AndroidJavaClass("android.widget.Toast");
			AndroidJavaObject toast = toastClass.CallStatic<AndroidJavaObject>("makeText", activity, message, 1);
			toast.Call("show");
		}));
#elif (ENABLE_HOLOLENS_MODULE_API || UNITY_5_5_OR_NEWER) && UNITY_WSA_10_0
		UnityEngine.WSA.Toast.Create("", message).Show();
#endif
		Debug.Log(message);
	}
}
