using System.Collections.Generic;
using System.Linq;
using BlueWest.Data;
using BlueWest.WebApi.MySQL;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
///
/// The controller responsible to fetch currency data
///
[ApiController]
[Route("[controller]")]
public class CurrenciesController : ControllerBase
{
private readonly CountriesDbContext _dbContext;
public CurrenciesController(CountriesDbContext dbContext)
{
_dbContext = dbContext;
}
///
/// Add Currency to the table of currencies
///
/// Currency data to create
///
[ProducesResponseType(StatusCodes.Status201Created)]
[HttpPost]
public ActionResult AddCurrency(CurrencyCreate currencyToCreate)
{
var newCurrency = new Currency(currencyToCreate, new List());
_dbContext.Currencies.Add(newCurrency);
_dbContext.SaveChanges();
return CreatedAtRoute(nameof(GetCurrencyById), new {CurrencyId = currencyToCreate.Code}, currencyToCreate);
}
///
/// Update a currency data from the Currency table in the database
///
/// The currency number we want to update
/// Currency Data to update
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut("{currencyNumber}")]
public ActionResult UpdateCurrency(int currencyNumber, CurrencyUpdate currencyToUpdate)
{
var currency = _dbContext.Currencies.FirstOrDefault(x => x.Num == currencyNumber);
if (currency != null)
{
var updatedCurrency = new Currency(currencyToUpdate, currencyNumber, new List());
_dbContext.Update(updatedCurrency);
_dbContext.SaveChanges();
return Ok(updatedCurrency);
}
return new NotFoundResult();
}
///
/// Gets a currency by the currency number (id)
///
/// The id of the currency to get
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{currencyId}", Name = nameof(GetCurrencyById))]
public ActionResult GetCurrencyById(int currencyId)
{
var array = _dbContext.Countries.FirstOrDefault(x => x.Code == currencyId);
if (array != null)
{
return Ok(array);
}
return new NotFoundResult();
}
}
}