using Microsoft.AspNetCore.Http.HttpResults;
using Microsoft.AspNetCore.Mvc;
using Strela.Models;
using Strela.Services;

namespace Strela.Controllers;

[ApiController]
[Route("api/[controller]")]
public class DeviceController : ControllerBase
{
    private readonly ILogger<DeviceController> _logger;

    public DeviceController(ILogger<DeviceController> logger)
    {
        _logger = logger;
    }

    //=========================== GET =================================//
    #region GET


    [HttpGet("GetDeviceById")]
    [ProducesResponseType<DeviceItem>(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public IActionResult GetById(Guid id) // Получить устройство по id
    {
        using (var db = new SQLiteService())
        {
            var d = db.Devices.Where(d => d.Id == id).FirstOrDefault();
            if (d != null)
                return Ok(d);
            else return NoContent();
        }
    }

    [HttpGet("GetDevices")]
    [ProducesResponseType<DeviceItem>(StatusCodes.Status200OK)]
    [ProducesResponseType(StatusCodes.Status204NoContent)]
    public IActionResult GetAll() // Получить все устройства
    {
        using (var db = new SQLiteService())
        {
            var d = db.Devices.ToList();
            //if (d.Count != 0)
            return Ok(d);
            //else return NoContent();
        }
    } 
    #endregion

    //========================= POST ====================================//
    #region POST
    [HttpPost("AddDevice")]
    public IActionResult AddDevice(DeviceItem d) // Добавить одно устройство
    {
        using (var db = new SQLiteService())
        {
            db.Devices.Add(d);//.Where(u => u.Name == name).FirstOrDefault();
            db.SaveChanges();
            return Created();
        }
    }

    
    #endregion

    //========================= DELETE ====================================//
    #region DELETE
    
    [HttpDelete("DelDevice")]
    public IActionResult DelDevice(Guid id) //Удалить  устройство по id
    {
        using (var db = new SQLiteService())
        {
            var deldev = db.Devices.Where(u => u.Id == id).FirstOrDefault();
            db.Devices.Remove(deldev);
            db.SaveChanges();
            return Ok();
        }
    } 
    #endregion
}
