/*==============================================================================
 * Copyright (c) 2012-2014 Qualcomm Connected Experiences, Inc. All Rights Reserved.
 *==============================================================================*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Linq;

public class UserDefinedTargetEventHandler : MonoBehaviour, IUserDefinedTargetEventHandler
{
    #region PUBLIC_MEMBERS
    /// <summary>
    /// Can be set in the Unity inspector to reference a ImageTargetBehaviour that is instanciated for augmentations of new user defined targets.
    /// </summary>
	/// 

    public ImageTargetBehaviour ImageTargetTemplate;
    #endregion PUBLIC_MEMBERS

    #region PRIVATE_MEMBERS
	private bool isTrackerTaken = false;
    private UserDefinedTargetBuildingBehaviour mTargetBuildingBehaviour;
    private ImageTracker mImageTracker;
    // DataSet that newly defined targets are added to
    private DataSet mBuiltDataSet;
    // currently observed frame quality
    private ImageTargetBuilder.FrameQuality mFrameQuality = ImageTargetBuilder.FrameQuality.FRAME_QUALITY_NONE;
    // counter variable used to name duplicates of the image target template
    private int mTargetCounter;
    private SampleAppUIButton mNewUserDefinedTargetButton;

    #endregion PRIVATE_MEMBERS

    /// <summary>
    /// Registers this component as a handler for UserDefinedTargetBuildingBehaviour events
    /// </summary>
    public void Init()
    {
        mTargetBuildingBehaviour = GetComponent<UserDefinedTargetBuildingBehaviour>();
        if (mTargetBuildingBehaviour)
        {
            mTargetBuildingBehaviour.RegisterEventHandler(this);
            Debug.Log ("Registering to the events of IUserDefinedTargetEventHandler");
        }

        mNewUserDefinedTargetButton = MakeUIButton();
        mNewUserDefinedTargetButton.TappedOn += OnTappedOnNewTargetButton;
    }

    public void Draw()
    {
		if(!isTrackerTaken)
        mNewUserDefinedTargetButton.Draw();
    }

    #region IUserDefinedTargetEventHandler implementation
    /// <summary>
    /// Called when UserDefinedTargetBuildingBehaviour has been initialized successfully
    /// </summary>
    public void OnInitialized ()
    {
        mImageTracker = TrackerManager.Instance.GetTracker<ImageTracker>();
        if (mImageTracker != null)
        {
            // create a new dataset
            mBuiltDataSet = mImageTracker.CreateDataSet();
            mImageTracker.ActivateDataSet(mBuiltDataSet);
        }
    }

    /// <summary>
    /// Updates the current frame quality
    /// </summary>
    public void OnFrameQualityChanged(ImageTargetBuilder.FrameQuality frameQuality)
    {
        mFrameQuality = frameQuality;
    }

    /// <summary>
    /// Takes a new trackable source and adds it to the dataset
    /// This gets called automatically as soon as you 'BuildNewTarget with UserDefinedTargetBuildingBehaviour
    /// </summary>
	public void OnNewTrackableSource(TrackableSource trackableSource)
	{
		OnNewTrackableSourceEnhanced (trackableSource, ImageTargetTemplate,ref mBuiltDataSet);
	}


	public void OnNewTrackableSourceEnhanced(TrackableSource trackableSource, ImageTargetBehaviour expectedImageTargetBehaviour,ref DataSet expectedDataSet)
	{
		
		expectedDataSet = mImageTracker.CreateDataSet();
		
		expectedDataSet.CreateTrackable(trackableSource, expectedImageTargetBehaviour.gameObject);

		mImageTracker.ActivateDataSet(expectedDataSet);

		StopExtendedTracking();
		
	}

    #endregion IUserDefinedTargetEventHandler implementation

    #region PRIVATE_METHODS
    /// <summary>
    /// Instantiates a new user-defined target and is also responsible for dispatching callback to 
    /// IUserDefinedTargetEventHandler::OnNewTrackableSource
    /// </summary>
    private void BuildNewTarget(ImageTargetBehaviour expectedImageTargetBehaviour)
    {
		mTargetBuildingBehaviour.BuildNewTarget(expectedImageTargetBehaviour.name, expectedImageTargetBehaviour.GetSize().x);
    }

    private void OnTappedOnNewTargetButton()
    {
        BuildNewTarget(ImageTargetTemplate);
		GameObject g = GameObject.FindGameObjectWithTag("CenterController")
									.GetComponent<CenterController>()
										.Get("VehicleChoice");
		g.SetActive(true);
		isTrackerTaken = true;

    }

    /// <summary>
    /// This method only demonstrates how to handle extended tracking feature when you have multiple targets in the scene
    /// So, this method could be removed otherwise
    /// </summary>
   private void StopExtendedTracking()
    {
        StateManager stateManager = TrackerManager.Instance.GetStateManager();
        
        //If the extended tracking is enabled, we first disable OTT for all the trackables
        //and then enable it for the newly created target
        //UDTUIEventHandler uiMenuEventHandler = FindObjectOfType(typeof(UDTUIEventHandler)) as UDTUIEventHandler;
        if(UDTUIEventHandler.ExtendedTrackingIsEnabled)
        {
            //Stop extended tracking on all the trackables
            foreach(var behaviour in stateManager.GetTrackableBehaviours())
            {
                var imageBehaviour = behaviour as ImageTargetBehaviour;
                if(imageBehaviour != null)
                {
                    imageBehaviour.ImageTarget.StopExtendedTracking();
                }
            }
    
            List<TrackableBehaviour> list =  stateManager.GetTrackableBehaviours().ToList();
            ImageTargetBehaviour bhvr = list[list.Count - 1] as ImageTargetBehaviour;
            if(bhvr != null)
            {
                bhvr.ImageTarget.StartExtendedTracking();
            }
        }
    }

    private SampleAppUIButton MakeUIButton()
    {
        Rect rect = new Rect(0.2f * Screen.width, Screen.height - (130 * Screen.width)/800.0f, 0.6f * Screen.width, (100.0f * Screen.width)/800.0f);
        GUIStyle style = new GUIStyle();
        style.normal.background = Resources.Load("UserInterface/capture_button_normal_XHigh") as Texture2D;
        style.active.background = Resources.Load("UserInterface/capture_button_normal_XHigh") as Texture2D;
        style.onNormal.background = Resources.Load("UserInterface/capture_button_normal_XHigh") as Texture2D;
        style.alignment = TextAnchor.MiddleCenter;
        Texture imageForButton = Resources.Load("UserInterface/icon_camera") as Texture;
        return new SampleAppUIButton(rect, style, imageForButton);
    }
    #endregion PRIVATE_METHODS
}



