using OnlineMaps;
using OnlineMaps.Webservices;
using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
    [ActionCategory(OnlineMapsCategories.GOOGLE)]
    [Tooltip("Gets returned result type by index from FindLocation response.")]
    public class GetLocationTypeByIndex : FsmStateAction
    {
        [RequiredField]
        [UIHint(UIHint.Variable)]
        [Tooltip("FindLocation response object")]
        public FsmObject responseObject;

        [RequiredField]
        [Tooltip("Location index")]
        public FsmInt locationIndex = 0;

        [RequiredField]
        [Tooltip("Type index")]
        public FsmInt typeIndex = 0;

        [UIHint(UIHint.Variable)]
        [Tooltip("Type of the returned result.")]
        public FsmString storeType;

        public override void Reset()
        {
            responseObject = null;
            locationIndex = 0;
            storeType = null;
        }

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

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

            if (responseObject.IsNone) return;

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

            FindLocationResponseWrapper wrapper = responseObject.Value as FindLocationResponseWrapper;
            if (locationIndex.Value < 0 || locationIndex.Value >= wrapper.count) return;

            GoogleGeocodingResult result = wrapper.results[locationIndex.Value];

            if (typeIndex.Value < 0 || typeIndex.Value >= result.types.Length) return;
            storeType.Value = result.types[typeIndex.Value];
        }
    }
}