package com.oguerreiro.resilient.web.rest;

import com.oguerreiro.resilient.repository.VariableUnitsRepository;
import com.oguerreiro.resilient.service.VariableUnitsService;
import com.oguerreiro.resilient.service.dto.VariableUnitsDTO;
import com.oguerreiro.resilient.web.rest.errors.BadRequestAlertException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import tech.jhipster.web.util.HeaderUtil;
import tech.jhipster.web.util.ResponseUtil;

/**
 * REST controller for managing {@link com.oguerreiro.resilient.domain.VariableUnits}.
 */
@RestController
@RequestMapping("/api/variable-units")
public class VariableUnitsResource {

    private final Logger log = LoggerFactory.getLogger(VariableUnitsResource.class);

    private static final String ENTITY_NAME = "variableUnits";

    @Value("${jhipster.clientApp.name}")
    private String applicationName;

    private final VariableUnitsService variableUnitsService;

    private final VariableUnitsRepository variableUnitsRepository;

    public VariableUnitsResource(VariableUnitsService variableUnitsService, VariableUnitsRepository variableUnitsRepository) {
        this.variableUnitsService = variableUnitsService;
        this.variableUnitsRepository = variableUnitsRepository;
    }

    /**
     * {@code POST  /variable-units} : Create a new variableUnits.
     *
     * @param variableUnitsDTO the variableUnitsDTO to create.
     * @return the {@link ResponseEntity} with status {@code 201 (Created)} and with body the new variableUnitsDTO, or with status {@code 400 (Bad Request)} if the variableUnits has already an ID.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PostMapping("")
    public ResponseEntity<VariableUnitsDTO> createVariableUnits(@RequestBody VariableUnitsDTO variableUnitsDTO) throws URISyntaxException {
        log.debug("REST request to save VariableUnits : {}", variableUnitsDTO);
        if (variableUnitsDTO.getId() != null) {
            throw new BadRequestAlertException("A new variableUnits cannot already have an ID", ENTITY_NAME, "idexists");
        }
        variableUnitsDTO = variableUnitsService.save(variableUnitsDTO);
        return ResponseEntity.created(new URI("/api/variable-units/" + variableUnitsDTO.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(applicationName, true, ENTITY_NAME, variableUnitsDTO.getId().toString()))
            .body(variableUnitsDTO);
    }

    /**
     * {@code PUT  /variable-units/:id} : Updates an existing variableUnits.
     *
     * @param id the id of the variableUnitsDTO to save.
     * @param variableUnitsDTO the variableUnitsDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated variableUnitsDTO,
     * or with status {@code 400 (Bad Request)} if the variableUnitsDTO is not valid,
     * or with status {@code 500 (Internal Server Error)} if the variableUnitsDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PutMapping("/{id}")
    public ResponseEntity<VariableUnitsDTO> updateVariableUnits(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody VariableUnitsDTO variableUnitsDTO
    ) throws URISyntaxException {
        log.debug("REST request to update VariableUnits : {}, {}", id, variableUnitsDTO);
        if (variableUnitsDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, variableUnitsDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!variableUnitsRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        variableUnitsDTO = variableUnitsService.update(variableUnitsDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, variableUnitsDTO.getId().toString()))
            .body(variableUnitsDTO);
    }

    /**
     * {@code PATCH  /variable-units/:id} : Partial updates given fields of an existing variableUnits, field will ignore if it is null
     *
     * @param id the id of the variableUnitsDTO to save.
     * @param variableUnitsDTO the variableUnitsDTO to update.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the updated variableUnitsDTO,
     * or with status {@code 400 (Bad Request)} if the variableUnitsDTO is not valid,
     * or with status {@code 404 (Not Found)} if the variableUnitsDTO is not found,
     * or with status {@code 500 (Internal Server Error)} if the variableUnitsDTO couldn't be updated.
     * @throws URISyntaxException if the Location URI syntax is incorrect.
     */
    @PatchMapping(value = "/{id}", consumes = { "application/json", "application/merge-patch+json" })
    public ResponseEntity<VariableUnitsDTO> partialUpdateVariableUnits(
        @PathVariable(value = "id", required = false) final Long id,
        @RequestBody VariableUnitsDTO variableUnitsDTO
    ) throws URISyntaxException {
        log.debug("REST request to partial update VariableUnits partially : {}, {}", id, variableUnitsDTO);
        if (variableUnitsDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        if (!Objects.equals(id, variableUnitsDTO.getId())) {
            throw new BadRequestAlertException("Invalid ID", ENTITY_NAME, "idinvalid");
        }

        if (!variableUnitsRepository.existsById(id)) {
            throw new BadRequestAlertException("Entity not found", ENTITY_NAME, "idnotfound");
        }

        Optional<VariableUnitsDTO> result = variableUnitsService.partialUpdate(variableUnitsDTO);

        return ResponseUtil.wrapOrNotFound(
            result,
            HeaderUtil.createEntityUpdateAlert(applicationName, true, ENTITY_NAME, variableUnitsDTO.getId().toString())
        );
    }

    /**
     * {@code GET  /variable-units} : get all the variableUnits.
     *
     * @param eagerload flag to eager load entities from relationships (This is applicable for many-to-many).
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of variableUnits in body.
     */
    @GetMapping("")
    public List<VariableUnitsDTO> getAllVariableUnits(
        @RequestParam(name = "eagerload", required = false, defaultValue = "true") boolean eagerload
    ) {
        log.debug("REST request to get all VariableUnits");
        return variableUnitsService.findAll();
    }

    /**
     * {@code GET  /variable-units/:id} : get the "id" variableUnits.
     *
     * @param id the id of the variableUnitsDTO to retrieve.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and with body the variableUnitsDTO, or with status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id}")
    public ResponseEntity<VariableUnitsDTO> getVariableUnits(@PathVariable("id") Long id) {
        log.debug("REST request to get VariableUnits : {}", id);
        Optional<VariableUnitsDTO> variableUnitsDTO = variableUnitsService.findOne(id);
        return ResponseUtil.wrapOrNotFound(variableUnitsDTO);
    }

    /**
     * {@code DELETE  /variable-units/:id} : delete the "id" variableUnits.
     *
     * @param id the id of the variableUnitsDTO to delete.
     * @return the {@link ResponseEntity} with status {@code 204 (NO_CONTENT)}.
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<Void> deleteVariableUnits(@PathVariable("id") Long id) {
        log.debug("REST request to delete VariableUnits : {}", id);
        variableUnitsService.delete(id);
        return ResponseEntity.noContent()
            .headers(HeaderUtil.createEntityDeletionAlert(applicationName, true, ENTITY_NAME, id.toString()))
            .build();
    }
}
