using System.Buffers.Text; using System.Text.Json; using System.Text.Json.Serialization; using Elements.Backend.DTOs; using Elements.Data; using Elements.Data.Models; using Microsoft.AspNetCore.Http.HttpResults; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; namespace Elements.Backend.Controllers; [ApiController] [Route("[controller]/[action]")] public class ElementController : ControllerBase { private readonly ApplicationDbContext _dbContext; public ElementController(ApplicationDbContext dbContext) { _dbContext = dbContext; } [Route("/element/{id:int}")] [HttpGet] public async Task GetElement(int id) { Element? element = await _dbContext.Elements .Include(e => e.User) .FirstOrDefaultAsync(e => e.Id == id); if (element == null) return NotFound(); var response = new ElementDTO() { Id = element.Id, Name = element.Name, CreatorName = element.User.Name, State = (int)element.State, Icon = Convert.ToBase64String(element.IconPng) }; var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; return Ok(JsonSerializer.Serialize(response, serializeOptions)); } [Route("/element/combine")] [HttpGet] public async Task GetByCombination(int firstElementId, int secondElementId) { bool firstExists = await _dbContext.Elements.AnyAsync(e => e.Id == firstElementId); bool secondExists = await _dbContext.Elements.AnyAsync(e => e.Id == secondElementId); if (!firstExists || !secondExists) return BadRequest(); Recipe? recipe = await _dbContext.Recipes.Include(r => r.ResultElement).ThenInclude(element => element.User).FirstOrDefaultAsync(r => (r.FirstElementId == firstElementId && r.SecondElementId == secondElementId) || (r.FirstElementId == secondElementId && r.SecondElementId == firstElementId)); if (recipe == null) return NotFound(); var response = new ElementDTO() { Id = recipe.ResultElement.Id, Name = recipe.ResultElement.Name, CreatorName = recipe.ResultElement.User.Name, State = (int)recipe.ResultElement.State, Icon = Convert.ToBase64String(recipe.ResultElement.IconPng) }; var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase }; return Ok(JsonSerializer.Serialize(response, serializeOptions)); } }