using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

namespace Assets.Scripts.Gameplay
{

    public class SteeringWheelController : MonoBehaviour
    {
        float _previousAngle = 0.1F;

        public static SteeringWheelController Instance;

        public float Steering;

        private Vector3 _wheelAngle;
        private Vector2 _lastPos;
        private float _lastAngle;

        private float _minAngle = -1080f;
        private float _maxAngle = 1080f;
        private float _minSteer = -45f;
        private float _maxSteer = 45f;

        void Awake()
        {
            Instance = this;
            _wheelAngle = transform.eulerAngles;
        }

        public void SetSteeringAngle(float x, float y)
        {
            var total = Mathf.Abs(x) + Mathf.Abs(y);
            if (total < 0.95f)
            {
                _lastPos = Vector2.zero;
                return;
            }

            var pos = new Vector2(x, y);

            if (_lastPos != Vector2.zero)
            {
                float angle = Mathf.Atan2(-x, y) * Mathf.Rad2Deg;
                if (angle < 0) angle += 360f;
                angle = 360 - angle;
                var dir = angle - _lastAngle;
                if (Mathf.Abs(dir) > 20f)
                {
                    _lastPos = pos;
                    _lastAngle = angle;
                    return;
                }
                _wheelAngle.z -= dir;
                _wheelAngle.z = Mathf.Clamp(_wheelAngle.z, _minAngle, _maxAngle);
                transform.eulerAngles = _wheelAngle;
                _lastAngle = angle;
            }
            SetSteerAngle();
            _lastPos = pos;
        }

        void SetSteerAngle()
        {
            var old = CarController.CarController.Instance.Steering;
            var newSteering = (((_wheelAngle.z - _minAngle) / (_maxAngle - _minAngle)) * (_maxSteer - _minSteer) + _minSteer) * -1;
            var dif = newSteering - old;
            CarController.CarController.Instance.Steering += dif;
        }
    }
}
