package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import com.google.api.client.util.Lists;
import io.github.jhipster.service.filter.IntegerFilter;
import org.springframework.data.domain.PageImpl;
import vn.azteam.tpf.Constants.Constants;
import vn.azteam.tpf.domain.TBSuppliesType;
import vn.azteam.tpf.service.TBExternalTableService;
import vn.azteam.tpf.service.TBSuppliesTypeService;
import vn.azteam.tpf.service.dto.TBControlTypeDTO;
import vn.azteam.tpf.service.dto.TBSuppliesTypeDTO;
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.TBExternalTableDTO;
import vn.azteam.tpf.service.dto.TBExternalTableCriteria;
import vn.azteam.tpf.service.TBExternalTableQueryService;
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 vn.azteam.tpf.web.rest.util.StreamUtil;

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

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

import static org.elasticsearch.index.query.QueryBuilders.*;

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

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

    private static final String ENTITY_NAME = "tBExternalTable";

    private final TBExternalTableService tBExternalTableService;

    private final TBExternalTableQueryService tBExternalTableQueryService;

    public TBExternalTableResource(TBExternalTableService tBExternalTableService, TBExternalTableQueryService tBExternalTableQueryService) {
        this.tBExternalTableService = tBExternalTableService;
        this.tBExternalTableQueryService = tBExternalTableQueryService;
    }

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

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

    /**
     * GET  /tb-external-tables : get all the tBExternalTables.
     *
     * @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 tBExternalTables in body
     */
    @GetMapping("/tb-external-tables")
    @Timed
    public ResponseEntity<List<TBExternalTableDTO>> getAllTBExternalTables(TBExternalTableCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBExternalTables by criteria: {}", criteria);
        Page<TBExternalTableDTO> page = tBExternalTableQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-external-tables");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-external-tables/count : count all the tBExternalTables.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-external-tables/count")
    @Timed
    public ResponseEntity<Long> countTBExternalTables(TBExternalTableCriteria criteria) {
        log.debug("REST request to count TBExternalTables by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBExternalTableQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-external-tables/:id : get the "id" tBExternalTable.
     *
     * @param id the id of the tBExternalTableDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBExternalTableDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-external-tables/{id}")
    @Timed
    public ResponseEntity<TBExternalTableDTO> getTBExternalTable(@PathVariable Long id) {
        log.debug("REST request to get TBExternalTable : {}", id);
        Optional<TBExternalTableDTO> tBExternalTableDTO = tBExternalTableService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBExternalTableDTO);
    }

    /**
     * DELETE  /tb-external-tables/:id : delete the "id" tBExternalTable.
     *
     * @param id the id of the tBExternalTableDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-external-tables/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBExternalTable(@PathVariable Long id) {
        log.debug("REST request to delete TBExternalTable : {}", id);
        tBExternalTableService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/tb-external-tables?query=:query : search for the tBExternalTable corresponding
     * to the query.
     *
     * @param query the query of the tBExternalTable search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/tb-external-tables")
    @Timed
    public ResponseEntity<List<TBExternalTableDTO>> searchTBExternalTables(@RequestParam String query, Pageable pageable) {
        log.debug("REST request to search for a page of TBExternalTables for query {}", query);
        Page<TBExternalTableDTO> page = tBExternalTableService.search(query, pageable);
        HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tb-external-tables");
        return new ResponseEntity<>(page.getContent(), headers, HttpStatus.OK);
    }

    @GetMapping("/extend-table-option/{type}")
    @Timed
    public ResponseEntity<List<TBExternalTableDTO>> getExtendTableOption(@PathVariable Integer type, Pageable pageable) {
        List<Object> result = new ArrayList<>();
        TBExternalTableCriteria criteria = new TBExternalTableCriteria();
        IntegerFilter objectTypeFilter = new IntegerFilter();
        objectTypeFilter.setEquals(type);
        criteria.setObjectType(objectTypeFilter);

        List<TBExternalTableDTO> tbExternalTableDTOs = tBExternalTableQueryService.findByCriteria(criteria);

        return ResponseEntity.ok().body(tbExternalTableDTOs);
    }
}
