package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import io.github.jhipster.service.filter.IntegerFilter;
import io.github.jhipster.service.filter.LongFilter;
import vn.azteam.tpf.Constants.Constants;
import vn.azteam.tpf.service.TBActivityExtendTypeService;
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.TBActivityExtendTypeDTO;
import vn.azteam.tpf.service.dto.TBActivityExtendTypeCriteria;
import vn.azteam.tpf.service.TBActivityExtendTypeQueryService;
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.List;
import java.util.Optional;
import java.util.stream.StreamSupport;

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

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

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

    private static final String ENTITY_NAME = "tBActivityExtendType";

    private final TBActivityExtendTypeService tBActivityExtendTypeService;

    private final TBActivityExtendTypeQueryService tBActivityExtendTypeQueryService;

    public TBActivityExtendTypeResource(TBActivityExtendTypeService tBActivityExtendTypeService, TBActivityExtendTypeQueryService tBActivityExtendTypeQueryService) {
        this.tBActivityExtendTypeService = tBActivityExtendTypeService;
        this.tBActivityExtendTypeQueryService = tBActivityExtendTypeQueryService;
    }

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

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

    /**
     * GET  /tb-activity-extend-types : get all the tBActivityExtendTypes.
     *
     * @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 tBActivityExtendTypes in body
     */
    @GetMapping("/tb-activity-extend-types")
    @Timed
    public ResponseEntity<List<TBActivityExtendTypeDTO>> getAllTBActivityExtendTypes(TBActivityExtendTypeCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBActivityExtendTypes by criteria: {}", criteria);
        Page<TBActivityExtendTypeDTO> page = tBActivityExtendTypeQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-activity-extend-types");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
    * GET  /tb-activity-extend-types/count : count all the tBActivityExtendTypes.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-activity-extend-types/count")
    @Timed
    public ResponseEntity<Long> countTBActivityExtendTypes(TBActivityExtendTypeCriteria criteria) {
        log.debug("REST request to count TBActivityExtendTypes by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBActivityExtendTypeQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-activity-extend-types/:id : get the "id" tBActivityExtendType.
     *
     * @param id the id of the tBActivityExtendTypeDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBActivityExtendTypeDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-activity-extend-types/{id}")
    @Timed
    public ResponseEntity<TBActivityExtendTypeDTO> getTBActivityExtendType(@PathVariable Long id) {
        log.debug("REST request to get TBActivityExtendType : {}", id);
        Optional<TBActivityExtendTypeDTO> tBActivityExtendTypeDTO = tBActivityExtendTypeService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBActivityExtendTypeDTO);
    }

    /**
     * DELETE  /tb-activity-extend-types/:id : delete the "id" tBActivityExtendType.
     *
     * @param id the id of the tBActivityExtendTypeDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-activity-extend-types/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBActivityExtendType(@PathVariable Long id) {
        log.debug("REST request to delete TBActivityExtendType : {}", id);
        tBActivityExtendTypeService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

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

    @GetMapping("/tb-activity-extend-types-child-list/{activityTypeId}")
    @Timed
    public ResponseEntity<List<TBActivityExtendTypeDTO>> getAllTBActivityExtendTypesChildList(@PathVariable Long activityTypeId,
                                                                                              Pageable pageable) {
        TBActivityExtendTypeCriteria criteria = new TBActivityExtendTypeCriteria();
        log.debug("REST request to get TBActivityExtendTypes by criteria: {}", criteria);
        IntegerFilter objectTypeFilter = new IntegerFilter();
        objectTypeFilter.setEquals(Constants.OBJECT_EXTEND_TYPE.TYPE_LIST.getValue());
        criteria.setObjectType(objectTypeFilter);

        LongFilter activityTypeFilter = new LongFilter();
        activityTypeFilter.setEquals(activityTypeId);
        criteria.setActivityTypeId(activityTypeFilter);

        Page<TBActivityExtendTypeDTO> page = tBActivityExtendTypeQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-activity-extend-types");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

}
