@page "/"

@using TestingRoom_NN_Kajk_UI.Models
@inject HttpClient HttpClient
@implements IDisposable

<PageTitle>Control</PageTitle>

<div class="row align-content-center text-center align-items-center">
    <div class="col-sm-12 col-xl-6 col-xxl-4">
        <h2><b>Otáčky: @RPM_Actual RPM</b></h2>
        <div class="progress" role="progressbar" aria-label="Basic example" aria-valuenow="@RPM_Actual" aria-valuemin="0" aria-valuemax="@RPM_Max">
            <div class="progress-bar" style="width: @($"{Math.Round((RPM_Actual / RPM_Max), 2) * 100}%")"></div>
        </div>
        <h3 />
    </div>

    <div class="col-sm-12 col-xl-6 col-xxl-4">
        <div class="align-content-center">
            <h4><b>Žádané otáčky:</b></h4>
            <div class="input-group mb-3">
                <input class="form-control text-center" type="number" min="0" max="@RPM_Max" value="@RPM_Requested" @onchange="(x) => SetRPMRequested(float.Parse(x.Value.ToString()))" />
            </div>

            <div>
                <button class="btn btn-primary" @onclick="() => AddRPMRequested(-1)">-1</button>
                <button class="btn btn-primary" @onclick="() => AddRPMRequested(+1)">+1</button>
                <button class="btn btn-primary" @onclick="() => AddRPMRequested(-10)">-10</button>
                <button class="btn btn-primary" @onclick="() => AddRPMRequested(+10)">+10</button>
                <button class="btn btn-primary" @onclick="() => AddRPMRequested(-100)">-100</button>
                <button class="btn btn-primary" @onclick="() => AddRPMRequested(100)">+100</button>
            </div>

            <h6 />

            <div>
                @foreach (int i in RPM_Presets)
                {
                    <button class="btn btn-primary" @onclick="() => SetRPMRequested(i)">@i RPM</button>
                }
            </div>
        </div>
        <h3 />
    </div>

    <div class="col-sm-12 col-xl-6 col-xxl-4">
        <h2><b>Rychlost náběhu: @(Math.Round(RPM_Acceleration_speed * 1000, 0)) </b></h2>
        <input type="range" class="form-range" min="1" max="1000" step="1" value="@(Math.Round(RPM_Acceleration_speed * 1000, 0).ToString())" @onchange="(x) => PostRPMAcceleration(float.Parse(x.Value.ToString()))" />
        <h3 />
    </div>

</div>






@code {
    string RPM_Actual_Variable_Name = "actual_rpm";
    string RPM_Requested_Variable_Name = "requested_rpm";
    string RPM_Max_Variable_Name = "max_rpm";
    string RPM_Acceleration_Variable_Name = "control_step_U";

    float RPM_Actual = 0;
    float RPM_Max = 1900;
    float RPM_Requested = 0;
    List<int> RPM_Presets = new() { 0, 1500, 1800 };

    float RPM_Acceleration_speed = 0;

    private System.Timers.Timer? RPM_Actual_Timer = new System.Timers.Timer(500); //actual RPM reader timer
    private System.Timers.Timer? RPM_Requested_Timer = new System.Timers.Timer(5000); //requested RPM reader timer
    private System.Timers.Timer? RPM_Max_Timer = new System.Timers.Timer(10000);    //max RPM reader timer
    private System.Timers.Timer? RPM_Acceleration_Timer = new System.Timers.Timer(1000);    //Acceleration RPM reader timer

    protected override void OnInitialized()
    {
        base.OnInitialized();

        //actual RPM request timer
        RPM_Actual_Timer.AutoReset = true;
        RPM_Actual_Timer.Elapsed += RequestActualRPM;
        RPM_Actual_Timer.Start();

        RequestRequestedRPM(null, null);
        GetRPMMax(null, null);
        GetRPMAcceleration(null, null);

        //requested RPM request timer
        RPM_Requested_Timer.AutoReset = true;
        RPM_Requested_Timer.Elapsed += RequestRequestedRPM;
        RPM_Requested_Timer.Start();

        //max RPM request timer
        RPM_Max_Timer.AutoReset = true;
        RPM_Max_Timer.Elapsed += GetRPMMax;
        RPM_Max_Timer.Start();

        //acceleration RPM request timer
        RPM_Acceleration_Timer.AutoReset = true;
        RPM_Acceleration_Timer.Elapsed += GetRPMAcceleration;
        RPM_Acceleration_Timer.Start();
    }

    private void SetRPMRequested(float rpm)
    {
        if (RPM_Requested_Timer == null)
            return;

        RPM_Requested_Timer.Stop();
        RPM_Requested = rpm;
        SetRPMRequested();
        RPM_Requested_Timer.Start();
    }

    private void AddRPMRequested(float add)
    {
        if (RPM_Requested_Timer == null)
            return;

        RPM_Requested_Timer.Stop();
        RPM_Requested += add;

        if (RPM_Requested < 0)
            RPM_Requested = 0;
        if (RPM_Requested > RPM_Max)
            RPM_Requested = RPM_Max;

        SetRPMRequested();
        RPM_Requested_Timer.Start();
    }

    private async void RequestActualRPM(object? sender, System.Timers.ElapsedEventArgs e)
    {
        string response = await HttpClient.GetStringAsync($"/api/variables/{RPM_Actual_Variable_Name}");
        if (float.TryParse(response.Replace("\"", "").Replace(".", ","), out float result))
        {
            RPM_Actual = result;
        }
        else
        {
            RPM_Actual = -1;
        }
        await InvokeAsync(StateHasChanged);
    }

    private async void RequestRequestedRPM(object? sender, System.Timers.ElapsedEventArgs? e)
    {
        RPM_Requested = int.Parse((await HttpClient.GetStringAsync($"/api/variables/{RPM_Requested_Variable_Name}")).Replace("\"", "").Replace(".", ","));
        await InvokeAsync(StateHasChanged);
    }

    private async void SetRPMRequested()
    {
        await HttpClient.PostAsJsonAsync($"/api/variables/{RPM_Requested_Variable_Name}", new VariablePostModel { data = RPM_Requested.ToString(), Isdefault = false });
    }

    private async void GetRPMMax(object? sender, System.Timers.ElapsedEventArgs? e)
    {
        RPM_Max = float.Parse((await HttpClient.GetStringAsync($"/api/variables/{RPM_Max_Variable_Name}")).Replace("\"", "").Replace(".", ","));
        await InvokeAsync(StateHasChanged);
    }


    private async void PostRPMAcceleration(float value)
    {
        if (RPM_Acceleration_Timer == null)
            return;

        RPM_Acceleration_Timer.Stop();

        RPM_Acceleration_speed = value / 1000;
        await InvokeAsync(StateHasChanged);
        await HttpClient.PostAsJsonAsync($"/api/variables/{RPM_Acceleration_Variable_Name}", new VariablePostModel { data = RPM_Acceleration_speed.ToString().Replace(",", "."), Isdefault = false });
        RPM_Acceleration_Timer.Start();
    }

    private async void GetRPMAcceleration(object? sender, System.Timers.ElapsedEventArgs? e)
    {
        RPM_Acceleration_speed = float.Parse((await HttpClient.GetStringAsync($"/api/variables/{RPM_Acceleration_Variable_Name}")).Replace("\"", "").Replace(".", ","));
    }



    private bool disposed;
    public void Dispose()
    {
        if (disposed) return;

        disposed = true;

        RPM_Actual_Timer.Stop();
        RPM_Actual_Timer.Dispose();
        RPM_Actual_Timer = null;

        RPM_Requested_Timer.Stop();
        RPM_Requested_Timer.Dispose();
        RPM_Requested_Timer = null;

        RPM_Max_Timer.Stop();
        RPM_Max_Timer.Dispose();
        RPM_Max_Timer = null;

        RPM_Acceleration_Timer.Stop();
        RPM_Acceleration_Timer.Dispose();
        RPM_Acceleration_Timer = null;

        this.Dispose();
    }
}