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

namespace HutongGames.PlayMaker.Actions
{
    [ActionCategory(OnlineMapsCategories.GOOGLE)]
    [Tooltip("Draw route on map by Google Directions or Open Route Service Directions response index.")]
    public class DrawRouteByIndex : FsmStateAction
    {
        [RequiredField]
        [Tooltip("Google Directions or Open Route response object.")]
        [UIHint(UIHint.Variable)]
        public FsmObject responseObject;

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

        [Tooltip("Line color.")]
        public FsmColor color = Color.green;

        [Tooltip("Line weight.")]
        public FsmFloat weight = 1;

        [UIHint(UIHint.Variable)]
        [Tooltip("Line drawing element.")]
        public FsmObject storeDrawingElement;

        public override void Reset()
        {
            responseObject = null;
            routeIndex = 0;
            color = Color.green;
            weight = 1;
            storeDrawingElement = 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 || wrapper.result == null) return;

                GeoPoint[] points = wrapper.result.routes[routeIndex.Value].polyline.points;
                Line line = new Line(points, color.Value, weight.Value);
                DrawingElementManager.AddItem(line);
                storeDrawingElement.Value = new DrawingElementWrapper(line);
            }
            else if (type == typeof(OpenRouteServiceDirectionsWrapper))
            {
                OpenRouteServiceDirectionsWrapper wrapper = responseObject.Value as OpenRouteServiceDirectionsWrapper;
                if (routeIndex.Value < 0 && routeIndex.Value >= wrapper.count) return;

                List<GeoPoint> points = wrapper.result.routes[routeIndex.Value].points;
                Line line = new Line(points, color.Value, weight.Value);
                DrawingElementManager.AddItem(line);
                storeDrawingElement.Value = new DrawingElementWrapper(line);
            }
            else
            {
                Debug.Log("Response Object is not FindDirectionResponseWrapper or OpenRouteServiceDirectionsWrapper instance");
            }
        }
    }
}