using System;
using System.Collections.Generic;
using System.Linq;
using OnlineMaps;
using OnlineMaps.Webservices;
using UnityEngine;

namespace HutongGames.PlayMaker.Actions
{
    [ActionCategory(OnlineMapsCategories.GOOGLE)]
    [Tooltip("Gets route from Google Directions or Open Route Service response object.")]
    public class GetRouteByIndex : FsmStateAction
    {
        [RequiredField]
        [Tooltip("FindDirection response object.")]
        [UIHint(UIHint.Variable)]
        public FsmObject responseObject;

        [RequiredField]
        [Tooltip("Route index.")]
        public FsmInt routeIndex = 0;

        [Tooltip("Route object.")]
        [UIHint(UIHint.Variable)]
        public FsmObject storeRouteObject;

        [Tooltip("Steps count.")]
        [UIHint(UIHint.Variable)]
        public FsmInt storeStepCount;

        public override void Reset()
        {
            responseObject = null;
            routeIndex = 0;
            storeRouteObject = null;
            storeStepCount = null;
        }

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

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

            if (responseObject.IsNone) return;

            Type type = responseObject.Value.GetType();
            if (type == typeof(FindDirectionResponseWrapper))
            {
                FindDirectionResponseWrapper wrapper = responseObject.Value as FindDirectionResponseWrapper;

                if (routeIndex.Value < 0 || routeIndex.Value >= wrapper.count) return;

                List<GoogleRoutingResult.RouteLegStep> steps = wrapper.result.routes[routeIndex.Value].legs.SelectMany(l => l.steps).ToList();
                storeRouteObject.Value = new RouteWrapper(steps);
                storeStepCount.Value = steps.Count;
            }
            else if (type == typeof(OpenRouteServiceDirectionsWrapper))
            {
                OpenRouteServiceDirectionsWrapper wrapper = responseObject.Value as OpenRouteServiceDirectionsWrapper;

                if (routeIndex.Value < 0 || routeIndex.Value >= wrapper.count) return;

                RouteWrapper routeWrapper = new RouteWrapper(wrapper.result.routes[routeIndex.Value]);
                storeRouteObject.Value = routeWrapper;
                storeStepCount.Value = routeWrapper.orsSteps.Count;
            }
            else
            {
                Debug.Log("Its not FindDirectionResponseWrapper or OpenRouteServiceDirectionsWrapper instance");
            }
        }
    }
}