summaryrefslogtreecommitdiff
path: root/backend/Elements.Backend/Controllers/ElementController.cs
blob: 2f57514da512a96469d5531009696655b592b0a6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
using System.Buffers.Text;
using System.Text.Json;
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<IActionResult> 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
        {
            Id = element.Id,
            Name = element.Name,
            CreatorName = element.User.Name,
            State = 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<IActionResult> 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).FirstOrDefaultAsync(r =>
            (r.FirstElementId == firstElementId && r.SecondElementId == secondElementId) ||
            (r.FirstElementId == secondElementId && r.SecondElementId == firstElementId));
        if (recipe == null)
            return NotFound();

        var serializeOptions = new JsonSerializerOptions { PropertyNamingPolicy = JsonNamingPolicy.CamelCase };
        return Ok(JsonSerializer.Serialize(recipe.ResultElement, serializeOptions));
    }
}