using System;
using System.Threading.Tasks;
using Controller.Bicycle;
using UnityEngine;

namespace SicknessReduction.Haptic
{
    public class FanController : EspController
    {
        private const int MAX_FAN_CYCLE = 256; //for RES=8
        private const float MAX_CYCLE_AT_SPEED = 6.94f; //25km/h
        private const int THRES_CYCLE_CHANGE = 3;
        private const int NUM_CHANNELS = 4;
        private const string TOPIC = "Fan/CHANNEL_NUMBER/Control";
        private const string CHANNEL_NUMBER_PLACEHOLDER = "CHANNEL_NUMBER";

        public RbBicycleController bicycleController;
        private int previousFanCycle;


        protected override async void Update()
        {
            base.Update();
            if (!DoUpdate || PreviousUpdateActive) return;
            PreviousUpdateActive = true;

            var cycle = FanCycleForSpeed();
            await SendFanCycles(cycle);

            PreviousUpdateActive = false;
        }

        private async Task SendFanCycles(int cycle)
        {
            if (Math.Abs(cycle - previousFanCycle) > THRES_CYCLE_CHANGE)
            {
                previousFanCycle = cycle;
                for (var i = 0; i < NUM_CHANNELS; i++)
                {
                    await Broker.Publish(TOPIC.Replace(CHANNEL_NUMBER_PLACEHOLDER, $"{i}"), $"{cycle}");
                }
            }
        }

        private int FanCycleForSpeed()
        {
            return (int) Mathf.Lerp(0f, MAX_FAN_CYCLE, bicycleController.CurrentSpeed / MAX_CYCLE_AT_SPEED);
        }
    }
}