@page "/database/type"
@using Ministreliy.Models
@using System.Text.Json
@using Newtonsoft.Json
@using System.Text

@inject IJSRuntime JS
@inject NavigationManager NavManager

<PageTitle>База данных</PageTitle>

<div class="modal fade modal1" id="addtype" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="addtypeLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="addtypeLabel">Заголовок</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <div class="mb-3">
                    <label for="typeID" class="form-label">id типа</label>
                    <input type="number" class="form-control" id="typeID" @bind="id_type" />
                </div>
                <div class="mb-3">
                    <label for="typeName" class="form-label">Имя типа</label>
                    <textarea class="form-control" id="typeName" rows="3" @bind="name_type"></textarea>
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" @onclick="SaveType">Сохранить</button>
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
            </div>
        </div>
    </div>
</div>


@if (listDT.Count == 0 || listDT == null)
{
    <p>@msg</p>
}
else
{
    <ul class="nav nav-tabs">
        <li class="nav-item" role="presentation">
            <a class="nav-link" aria-current="page" href="database">Сводные данные</a>
        </li>
        <li class="nav-item" role="presentation">
            <a class="nav-link active"
               id="addtype-tab"
               data-bs-toggle="tab"
               data-bs-target="#addtype"
               role="tab"
               aria-controls="addtype"
               aria-selected="true"
               href="database/addtype">Добавить Тип</a>
        </li>

    </ul>

    <div class="card-body p-0">
        <div class="tab-content" id="myTabContent">
            <!-- Панель 1: Главная -->
            <div class="tab-pane fade show active" id="addtype" role="tabpanel" aria-labelledby="addtype-tab">
                <table class="table">
                    <thead>
                        <tr>
                            <th scope="col">#</th>
                            <th scope="col">Название</th>
                        </tr>
                    </thead>
                    <tbody>
                        @foreach (var item in listDT)
                        {
                            <tr>
                                <th scope="row">@item.Id</th>
                                <td>@item.Name</td>
                            </tr>
                        }
                    </tbody>
                </table>
            </div>
        </div>
    </div>


    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#deltype">
        Удалить тип
    </button>



    <div class="modal fade modal2" id="deltype" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="deltypeLabel" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h1 class="modal-title fs-5" id="deltypeLabel">Заголовок</h1>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <div class="mb-3">
                        <select class="form-select" @bind="selected_type" aria-label="Вибрать тип">
                            @foreach (var item in listDT)
                            {
                                <option value="@item.Id">@item.Name</option>
                            }
                        </select>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" @onclick="DelType">Удалить</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Закрыть</button>
                </div>
            </div>
        </div>
    </div>
}
    <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#addtype">
        Добавить тип
    </button>

@code {
    //HttpClient http = new();

    private DeviceType dt;
    private List<DeviceType> listDT = new();

    private string msg = "-= ПОЛУЧАЮ ДАННЫЕ =-", name_type = "";
    private int id_type = 1, selected_type = 0;

    protected override async Task OnInitializedAsync()
    {
        HttpClient http = new();
        await Task.Delay(1000);
        http.BaseAddress = new Uri("http://localhost:5262/api/");
        var t = await http.GetAsync("Device/GetTypes");
        if (t.StatusCode == System.Net.HttpStatusCode.NoContent)
        {
            msg = "-= ДАННЫХ НЕТ =-";
        }
        else
        {
            listDT = JsonConvert.DeserializeObject<List<DeviceType>>(await t.Content.ReadAsStringAsync());
            //id_type = listDT.Count + 1;
            var a = listDT.Select(listDT => listDT.Id).ToList();
            id_type = Enumerable.Range(1, int.MaxValue).FirstOrDefault(i => !a.Contains(i));
        }
    }
    private async Task SaveType()
    {
        HttpClient http = new();
        dt = new();
        dt.Id = id_type;
        dt.Name = name_type;
        http.BaseAddress = new Uri("http://localhost:5262/api/");
        using StringContent content = new StringContent(
            JsonConvert.SerializeObject(dt),
            Encoding.UTF8,
            "application/json"
        );
        var r = await http.PostAsync("Device/AddType", content);
        if (r.IsSuccessStatusCode)
        {
            await JS.InvokeVoidAsync("eval", $"var myModal = bootstrap.Modal.getInstance(document.querySelector('.modal1')); myModal.hide();");
            await Task.Delay(150);
            id_type = listDT.Count+1;
            NavManager.NavigateTo(NavManager.Uri, forceLoad: true);
        }
    }
    private async Task DelType()
    {
        HttpClient http = new();
        http.BaseAddress = new Uri("http://localhost:5262/api/");
        var r = await http.DeleteAsync($"Device/DelType?id={selected_type}");
        if (r.IsSuccessStatusCode)
        {
            await JS.InvokeVoidAsync("eval", $"var myModal = bootstrap.Modal.getInstance(document.querySelector('.modal2')); myModal.hide();");
            await Task.Delay(250);
            id_type = listDT.Count + 1;
            NavManager.NavigateTo(NavManager.Uri, forceLoad: true);
        }
    }
}


