using System;
using Controller.Bicycle;
using Controller.Lean;
using Sensors;
using Sensors.ANT;
using Sensors.Polar;
using Tracking;
using UnityEngine;
using UnityEngine.Serialization;

namespace Controller
{
    [Serializable]
    public struct FrontWheelTrackerConfig
    {
        public FrontWheelTracker frontWheelTracker;
        public float multiplicator;

        public float AdjustedRotation => frontWheelTracker.SteerRotation * multiplicator;
    }

    [RequireComponent(typeof(IBicycleController))]
    public class SensorBikeController : MonoBehaviour
    {
        public PolarRotationMapping polarRotationMapping;
        public FrontWheelTrackerConfig frontWheelTrackerConfig;

        public bool steer = true;
        public bool accelerate = true;
        public bool lean = true;

        private IBicycleController bicycleController;
        private BikeSensorData sensorData;
        private bool isFrontWheelTrackerNotNull;

        private void Start()
        {
            isFrontWheelTrackerNotNull = frontWheelTrackerConfig.frontWheelTracker != null;
            bicycleController = GetComponent<IBicycleController>();
            sensorData = BikeSensorData.Instance;
        }

        private void Update()
        {
            var speedData = sensorData.SpeedData;

            if (speedData != null && accelerate)
            {
                SetSpeed(speedData.Value);
            }

            if (isFrontWheelTrackerNotNull && steer)
            {
                SetSteer();
            }

            if (lean)
            {
                SetLeaningAngle();
            }
        }

        private void SetSteer()
        {
            bicycleController.CurrentSteerAngle =
                frontWheelTrackerConfig.AdjustedRotation;
        }
        private void SetLeaningAngle()
        {
            //bicycleController.CurrentLeaningAngle = 
        }

        private void SetSpeed(SpeedSensorData speedData)
        {
            bicycleController.CurrentSpeed = speedData.Speed;
        }
    }
}