using OnlineMaps;
using OnlineMaps.Webservices;
using UnityEngine;

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

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

        [RequiredField]
        [Tooltip("Postcode locality index")]
        public FsmInt postcodeIndex = 0;

        [UIHint(UIHint.Variable)]
        [Tooltip("Locality contained in a postal code.")]
        public FsmString storePostcodeLocality;

        public override void Reset()
        {
            responseObject = null;
            locationIndex = 0;
            storePostcodeLocality = 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 (postcodeIndex.Value < 0 || postcodeIndex.Value >= result.types.Length) return;
            storePostcodeLocality.Value = result.postcode_localities[postcodeIndex.Value];
        }
    }
}