using System.Collections.Generic;
using System.Linq;
using BlueWest.Data;
using BlueWest.WebApi.EF;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace BlueWest.WebApi.Controllers
{
///
/// Controller responsible to get country data
///
[ApiController]
[Route("[controller]")]
internal class CountryController : ControllerBase
{
private readonly CountryDbContext _dbContext;
///
/// Controller responsible for handling country data in the Country table
///
///
public CountryController(CountryDbContext dbContext)
{
_dbContext = dbContext;
}
///
/// Add Country
///
/// The country data to create
/// The newly created country
/// ///
/// Creates a Country.
///
///
/// Sample request:
///
/// POST /Countries
/// {
/// "code": 1,
/// "stateName": "United States of America",
/// "tld": "us"
/// }
///
///
/// Returns the newly created country
[ProducesResponseType(StatusCodes.Status201Created)]
[HttpPost]
public ActionResult AddCountry(CountryCreate countryToCreate)
{
_dbContext.AddCountry(countryToCreate);
return CreatedAtRoute(nameof(GetCountryById), new {countryId = countryToCreate.Code});
}
///
/// Updates a Country
///
/// The country ISO 3166 code
/// Country payload data
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status400BadRequest)]
[HttpPut("{countryCode}")]
public ActionResult UpdateCountry(int countryCode, CountryUpdate countryToUpdate)
{
var (success, country) = _dbContext.UpdateCountry(countryToUpdate, countryCode);
if (success)
{
return Ok(country);
}
return new NotFoundResult();
}
///
/// Get countries
///
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet]
public ActionResult GetCountries()
{
var array = _dbContext.Countries;
if (array != null)
{
return Ok(array.ToArray());
}
return new NotFoundResult();
}
///
/// Get Country by Id
///
/// ISO 3166-1 country numeric code
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{countryId}", Name = nameof(GetCountryById))]
public ActionResult GetCountryById(int countryId)
{
var array = _dbContext.Countries.FirstOrDefault(x => x.Code == countryId);
if (array != null)
{
return Ok(array);
}
return new NotFoundResult();
}
///
/// Get currencies of a country
///
///
///
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
[HttpGet("{countryId}/currencies")]
public ActionResult GetCountryCurrencies(int countryId)
{
var country = _dbContext.Countries.FirstOrDefault(d => d.Code == countryId);
if (country == null) return new NotFoundResult();
var array = _dbContext
.Countries
.Where(data => data.Code == countryId)
.SelectMany(o => o.Currencies)
.ToArray();
return Ok(array);
}
}
}