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 io.github.jhipster.service.filter.LongFilter;
import org.springframework.data.domain.PageImpl;
import vn.azteam.tpf.Constants.Constants;
import vn.azteam.tpf.domain.TBExternalTable;
import vn.azteam.tpf.service.*;
import vn.azteam.tpf.service.dto.*;
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 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.*;
import java.util.stream.Collectors;

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

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

    private static final String ENTITY_NAME = "tBControlType";

    private final TBControlTypeService tBControlTypeService;

    private final TBControlTypeQueryService tBControlTypeQueryService;

    private final TBObjectParameterService tbObjectParameterService;

    public TBControlTypeResource(TBControlTypeService tBControlTypeService,
                                 TBControlTypeQueryService tBControlTypeQueryService,
                                 TBObjectParameterService tbObjectParameterService) {
        this.tBControlTypeService = tBControlTypeService;
        this.tBControlTypeQueryService = tBControlTypeQueryService;
        this.tbObjectParameterService = tbObjectParameterService;
    }

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

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

    /**
     * GET  /tb-control-types : get all the tBControlTypes.
     *
     * @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 tBControlTypes in body
     */
    @GetMapping("/tb-control-types")
    @Timed
    public ResponseEntity<List<TBControlTypeDTO>> getAllTBControlTypes(TBControlTypeCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBControlTypes by criteria: {}", criteria);
        Page<TBControlTypeDTO> page = tBControlTypeQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-control-types");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-control-types/count : count all the tBControlTypes.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-control-types/count")
    @Timed
    public ResponseEntity<Long> countTBControlTypes(TBControlTypeCriteria criteria) {
        log.debug("REST request to count TBControlTypes by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBControlTypeQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-control-types/:id : get the "id" tBControlType.
     *
     * @param id the id of the tBControlTypeDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBControlTypeDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-control-types/{id}")
    @Timed
    public ResponseEntity<TBControlTypeDTO> getTBControlType(@PathVariable Long id) {
        log.debug("REST request to get TBControlType : {}", id);
        Optional<TBControlTypeDTO> tBControlTypeDTO = tBControlTypeService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBControlTypeDTO);
    }

    /**
     * DELETE  /tb-control-types/:id : delete the "id" tBControlType.
     *
     * @param id the id of the tBControlTypeDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-control-types/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBControlType(@PathVariable Long id) {
        log.debug("REST request to delete TBControlType : {}", id);
        tBControlTypeService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

    @GetMapping("/tb-control-types-option/{type}")
    @Timed
    public ResponseEntity<List<TBControlTypeDTO>> getTBControlTypesOption(@PathVariable String type, Pageable pageable) {
        TBControlTypeCriteria criteria = new TBControlTypeCriteria();
        List<TBControlTypeDTO> result = tBControlTypeQueryService.findByCriteria(criteria, pageable).getContent();
        List<String> nonTextControls = Arrays.asList(Constants.NON_TEXT_CONTROLS);
        switch (type){
            case "param":
                result = result.stream()
                    .filter(item -> !nonTextControls.contains(item.getName()))
                    .collect(Collectors.toList());
                break;
            case "object":
                result = result.stream()
                    .filter(item -> nonTextControls.contains(item.getName()))
                    .collect(Collectors.toList());
                break;
            default:
                break;
        }
        return ResponseEntity.ok().body(result);
    }
}
