using OnlineMaps;
using OnlineMaps.Webservices;
using UnityEngine;

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

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

        [RequiredField]
        [Tooltip("Address component index")]
        public FsmInt addressComponentIndex = 0;

        [UIHint(UIHint.Variable)]
        [Tooltip("Count of address component types.")]
        public FsmInt storeTypesCount;

        [UIHint(UIHint.Variable)]
        [Tooltip("Full text description or name of the address component as returned by the Geocoder.")]
        public FsmString storeLongName;

        [UIHint(UIHint.Variable)]
        [Tooltip("Abbreviated textual name for the address component, if available.")]
        public FsmString storeShortName;

        public override void Reset()
        {
            responseObject = null;
            locationIndex = 0;
            storeTypesCount = null;
            storeLongName = null;
            storeShortName = 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];
            GoogleGeocodingResult.AddressComponent[] acs = result.address_components;
            if (addressComponentIndex.Value < 0 || addressComponentIndex.Value >= acs.Length) return;

            GoogleGeocodingResult.AddressComponent ac = acs[addressComponentIndex.Value];

            storeTypesCount.Value = ac.types.Length;
            storeLongName.Value = ac.long_name;
            storeShortName.Value = ac.short_name;
        }
    }
}