package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.google.common.collect.Lists;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;
import vn.azteam.tpf.service.TBCropQueryService;
import vn.azteam.tpf.service.TBCustomerHasCropTypeService;
import vn.azteam.tpf.service.dto.TBCustomerHasCropTypeUpdateDTO;
import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;
import vn.azteam.tpf.web.rest.util.HeaderUtil;
import vn.azteam.tpf.web.rest.util.PaginationUtil;
import vn.azteam.tpf.service.dto.TBCustomerHasCropTypeDTO;
import vn.azteam.tpf.service.dto.TBCustomerHasCropTypeCriteria;
import vn.azteam.tpf.service.TBCustomerHasCropTypeQueryService;
import io.github.jhipster.web.util.ResponseUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.net.URI;
import java.net.URISyntaxException;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * REST controller for managing TBCustomerHasCropType.
 */
@RestController
@RequestMapping("/api")
public class TBCustomerHasCropTypeResource {

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

    private static final String ENTITY_NAME = "tBCustomerHasCropType";

    private final TBCustomerHasCropTypeService tBCustomerHasCropTypeService;

    private final TBCustomerHasCropTypeQueryService tBCustomerHasCropTypeQueryService;

    public TBCustomerHasCropTypeResource(TBCustomerHasCropTypeService tBCustomerHasCropTypeService, TBCustomerHasCropTypeQueryService tBCustomerHasCropTypeQueryService) {
        this.tBCustomerHasCropTypeService = tBCustomerHasCropTypeService;
        this.tBCustomerHasCropTypeQueryService = tBCustomerHasCropTypeQueryService;
    }

    /**
     * POST  /tb-customer-has-crop-types : Create a new tBCustomerHasCropType.
     *
     * @param tBCustomerHasCropTypeDTO the tBCustomerHasCropTypeDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new tBCustomerHasCropTypeDTO, or with status 400 (Bad Request) if the tBCustomerHasCropType has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/tb-customer-has-crop-types")
    @Timed
    public ResponseEntity<TBCustomerHasCropTypeDTO> createTBCustomerHasCropType(@RequestBody TBCustomerHasCropTypeDTO tBCustomerHasCropTypeDTO) throws URISyntaxException {
        log.debug("REST request to save TBCustomerHasCropType : {}", tBCustomerHasCropTypeDTO);
        if (tBCustomerHasCropTypeDTO.getId() != null) {
            throw new BadRequestAlertException("A new tBCustomerHasCropType cannot already have an ID", ENTITY_NAME, "idexists");
        }
        TBCustomerHasCropTypeDTO result = tBCustomerHasCropTypeService.save(tBCustomerHasCropTypeDTO);
        return ResponseEntity.created(new URI("/api/tb-customer-has-crop-types/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }

    /**
     * PUT  /tb-customer-has-crop-types : Updates an existing tBCustomerHasCropType.
     *
     * @param tBCustomerHasCropTypeDTO the tBCustomerHasCropTypeDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated tBCustomerHasCropTypeDTO,
     * or with status 400 (Bad Request) if the tBCustomerHasCropTypeDTO is not valid,
     * or with status 500 (Internal Server Error) if the tBCustomerHasCropTypeDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/tb-customer-has-crop-types")
    @Timed
    public ResponseEntity<TBCustomerHasCropTypeDTO> updateTBCustomerHasCropType(@RequestBody TBCustomerHasCropTypeDTO tBCustomerHasCropTypeDTO) throws URISyntaxException {
        log.debug("REST request to update TBCustomerHasCropType : {}", tBCustomerHasCropTypeDTO);
        if (tBCustomerHasCropTypeDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        TBCustomerHasCropTypeDTO result = tBCustomerHasCropTypeService.save(tBCustomerHasCropTypeDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBCustomerHasCropTypeDTO.getId().toString()))
            .body(result);
    }

    @GetMapping("/setting-crop-and-activity-by-customer/{id}")
    @Timed
    public ResponseEntity<TBCustomerHasCropTypeUpdateDTO> getSettingCropAndActivityByCustomer(@PathVariable Long id, Pageable pageable){
        if (id == null) {
            throw new BadRequestAlertException("1040", ENTITY_NAME, "1040");
        }
        TBCustomerHasCropTypeUpdateDTO result = tBCustomerHasCropTypeQueryService.getCustomerHasCropTypeUpdate(id, pageable);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, id.toString()))
            .body(result);
    }

    @PutMapping("/setting-crop-and-activity")
    @Transactional
    public ResponseEntity<TBCustomerHasCropTypeUpdateDTO> updateTBCustomerHasCropTypeByActivityType(@RequestBody TBCustomerHasCropTypeUpdateDTO tbCustomerHasCropTypeUpdateDTO, Pageable pageable) {
        log.debug("REST request to update TBCustomerHasCropTypeUpdateDTO : {}", tbCustomerHasCropTypeUpdateDTO);
        if (tbCustomerHasCropTypeUpdateDTO.getTbCustomerId() == null) {
            throw new BadRequestAlertException("1040", ENTITY_NAME, "1040");
        }
        TBCustomerHasCropTypeUpdateDTO result = new TBCustomerHasCropTypeUpdateDTO();
        boolean updateCheck = tBCustomerHasCropTypeQueryService.updateCustomerHasCropTypeUpdate(tbCustomerHasCropTypeUpdateDTO);
        if(updateCheck){
            result = tBCustomerHasCropTypeQueryService.getCustomerHasCropTypeUpdate(tbCustomerHasCropTypeUpdateDTO.getTbCustomerId(), pageable);
        }
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, result.getTbCustomerId().toString()))
            .body(result);
    }

    /**
     * GET  /tb-customer-has-crop-types : get all the tBCustomerHasCropTypes.
     *
     * @param pageable the pagination information
     * @param criteria the criterias which the requested entities should match
     * @return the ResponseEntity with status 200 (OK) and the list of tBCustomerHasCropTypes in body
     */
    @GetMapping("/tb-customer-has-crop-types")
    @Timed
    public ResponseEntity<List<TBCustomerHasCropTypeDTO>> getAllTBCustomerHasCropTypes(TBCustomerHasCropTypeCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBCustomerHasCropTypes by criteria: {}", criteria);
        Page<TBCustomerHasCropTypeDTO> page = tBCustomerHasCropTypeQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-customer-has-crop-types");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-customer-has-crop-types/count : count all the tBCustomerHasCropTypes.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-customer-has-crop-types/count")
    @Timed
    public ResponseEntity<Long> countTBCustomerHasCropTypes(TBCustomerHasCropTypeCriteria criteria) {
        log.debug("REST request to count TBCustomerHasCropTypes by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBCustomerHasCropTypeQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-customer-has-crop-types/:id : get the "id" tBCustomerHasCropType.
     *
     * @param id the id of the tBCustomerHasCropTypeDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBCustomerHasCropTypeDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-customer-has-crop-types/{id}")
    @Timed
    public ResponseEntity<TBCustomerHasCropTypeDTO> getTBCustomerHasCropType(@PathVariable Long id) {
        log.debug("REST request to get TBCustomerHasCropType : {}", id);
        Optional<TBCustomerHasCropTypeDTO> tBCustomerHasCropTypeDTO = tBCustomerHasCropTypeService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBCustomerHasCropTypeDTO);
    }

    /**
     * DELETE  /tb-customer-has-crop-types/:id : delete the "id" tBCustomerHasCropType.
     *
     * @param id the id of the tBCustomerHasCropTypeDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-customer-has-crop-types/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBCustomerHasCropType(@PathVariable Long id) {
        log.debug("REST request to delete TBCustomerHasCropType : {}", id);
        tBCustomerHasCropTypeService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/tb-customer-has-crop-types?query=:query : search for the tBCustomerHasCropType corresponding
     * to the query.
     *
     * @param query the query of the tBCustomerHasCropType search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/tb-customer-has-crop-types")
    @Timed
    public ResponseEntity<List<TBCustomerHasCropTypeDTO>> searchTBCustomerHasCropTypes(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of TBCustomerHasCropTypes for query {}", query);
        Page<TBCustomerHasCropTypeDTO> page = tBCustomerHasCropTypeService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tb-customer-has-crop-types");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

}
