﻿using OnlineMaps;
using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
    [ActionCategory(OnlineMapsCategories.MARKERS)]
    [Tooltip("Get the index of marker")]
    public class GetMarkerIndex : FsmStateAction
    {
        [RequiredField]
        [UIHint(UIHint.Variable)]
        [Tooltip("Instance of marker.")]
        public FsmObject marker;

        [RequiredField]
        [UIHint(UIHint.Variable)]
        [Tooltip("Index of marker.")]
        public FsmInt storeIndex;

        public override void Reset()
        {
            marker = null;
            storeIndex = null;
        }

        public override void OnEnter()
        {
            DoEnter();
            Finish();
        }

        private void DoEnter()
        {
            Map map = Map.instance;
            if (!map)
            {
                Debug.LogError("Online Maps not found.");
                return;
            }

            if (marker.IsNone || storeIndex.IsNone) return;

            if (marker.Value.GetType() != typeof(MarkerWrapper))
            {
                Debug.Log("Its not MarkerWrapper instance");
                return;
            }

            Marker m = (marker.Value as MarkerWrapper).marker;
            if (m is Marker2D)
            {
                for (int i = 0; i < map.marker2DManager.count; i++)
                {
                    if (map.marker2DManager[i] == m)
                    {
                        storeIndex.Value = i;
                        break;
                    }
                }
            }
            else if (m is Marker3D)
            {
                for (int i = 0; i < map.marker3DManager.count; i++)
                {
                    if (map.marker3DManager[i] == m)
                    {
                        storeIndex.Value = i;
                        break;
                    }
                }
            }
        }
    }
}