package vn.azteam.tpf.web.rest;

import com.codahale.metrics.annotation.Timed;
import vn.azteam.tpf.service.TBCustomerService;
import vn.azteam.tpf.service.TBRoleService;
import vn.azteam.tpf.service.UserService;
import vn.azteam.tpf.service.dto.TBRoleDTO;
import vn.azteam.tpf.service.dto.UserDTO;
import vn.azteam.tpf.service.util.UserRoleUtil;
import vn.azteam.tpf.web.rest.errors.BadRequestAlertException;
import vn.azteam.tpf.web.rest.errors.ForbiddenException;
import vn.azteam.tpf.web.rest.util.HeaderUtil;
import vn.azteam.tpf.web.rest.util.PaginationUtil;
import vn.azteam.tpf.service.dto.TBCustomerDTO;
import vn.azteam.tpf.service.dto.TBCustomerCriteria;
import vn.azteam.tpf.service.TBCustomerQueryService;
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.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.net.URI;
import java.net.URISyntaxException;

import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

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

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

    private static final String ENTITY_NAME = "tBCustomer";

    private final TBCustomerService tBCustomerService;

    private final TBCustomerQueryService tBCustomerQueryService;

    private final TBRoleService tbRoleService;

    private final UserService userService;

    private final UserRoleUtil userRoleUtil;

    public TBCustomerResource(TBCustomerService tBCustomerService, TBCustomerQueryService tBCustomerQueryService, TBRoleService tbRoleService, UserService userService, UserRoleUtil userRoleUtil) {
        this.tBCustomerService = tBCustomerService;
        this.tBCustomerQueryService = tBCustomerQueryService;
        this.tbRoleService = tbRoleService;
        this.userService = userService;
        this.userRoleUtil = userRoleUtil;
    }

    /**
     * POST  /tb-customers : Create a new tBCustomer.
     *
     * @param tBCustomerDTO the tBCustomerDTO to create
     * @return the ResponseEntity with status 201 (Created) and with body the new tBCustomerDTO, or with status 400 (Bad Request) if the tBCustomer has already an ID
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PostMapping("/tb-customers")
    @Timed
    public ResponseEntity<TBCustomerDTO> createTBCustomer(@RequestBody TBCustomerDTO tBCustomerDTO) throws URISyntaxException {
        log.debug("REST request to save TBCustomer : {}", tBCustomerDTO);
        if (tBCustomerDTO.getId() != null) {
            throw new BadRequestAlertException("A new tBCustomer cannot already have an ID", ENTITY_NAME, "idexists");
        }
        tBCustomerDTO.setApiKey(this.createApiKey());
        TBCustomerDTO result = tBCustomerQueryService.createCustomer(tBCustomerDTO);
        return ResponseEntity.created(new URI("/api/tb-customers/" + result.getId()))
            .headers(HeaderUtil.createEntityCreationAlert(ENTITY_NAME, result.getId().toString()))
            .body(result);
    }
    public String createApiKey(){
        return UUID.randomUUID().toString();
    }
    /**
     * PUT  /tb-customers : Updates an existing tBCustomer.
     *
     * @param tBCustomerDTO the tBCustomerDTO to update
     * @return the ResponseEntity with status 200 (OK) and with body the updated tBCustomerDTO,
     * or with status 400 (Bad Request) if the tBCustomerDTO is not valid,
     * or with status 500 (Internal Server Error) if the tBCustomerDTO couldn't be updated
     * @throws URISyntaxException if the Location URI syntax is incorrect
     */
    @PutMapping("/tb-customers")
    @Timed
    public ResponseEntity<TBCustomerDTO> updateTBCustomer(@RequestBody TBCustomerDTO tBCustomerDTO) throws URISyntaxException {
        log.debug("REST request to update TBCustomer : {}", tBCustomerDTO);
        if (tBCustomerDTO.getId() == null) {
            throw new BadRequestAlertException("Invalid id", ENTITY_NAME, "idnull");
        }
        TBCustomerDTO result = tBCustomerQueryService.updateCustomer(tBCustomerDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tBCustomerDTO.getId().toString()))
            .body(result);
    }

    @PutMapping("/tb-customers-api-key/{customerId}")
    @Timed
    public ResponseEntity<TBCustomerDTO> updateTBCustomerApiKey(@PathVariable Long customerId) {
        log.debug("REST request to update Api-Key TBCustomer");
        if (customerId == null){
            throw new BadRequestAlertException("Invalid customer", ENTITY_NAME, "customeridnull");
        }
        Optional<TBCustomerDTO> tbCustomerDTOOptional = tBCustomerService.findOne(customerId);
        if (!tbCustomerDTOOptional.isPresent()){
            throw new BadRequestAlertException("Customer not found", ENTITY_NAME, "customernotfound");
        }
        UserDTO currentUser = userService.getCurrentUserDTO().get();
//        if(currentUser.getCustomerId() != null && !currentUser.getCustomerId().equals(customerId)){
//            throw new ForbiddenException();
//        }
        if (currentUser.getCustomerId() != null){
            throw new ForbiddenException();
        }
        String apiKeyNew = this.createApiKey();
        TBCustomerDTO tbCustomerDTO = tbCustomerDTOOptional.get();
        tbCustomerDTO.setApiKey(apiKeyNew);
        TBCustomerDTO result = tBCustomerQueryService.updateCustomer(tbCustomerDTO);
        return ResponseEntity.ok()
            .headers(HeaderUtil.createEntityUpdateAlert(ENTITY_NAME, tbCustomerDTO.getId().toString()))
            .body(result);
    }
    /**
     * GET  /tb-customers : get all the tBCustomers.
     *
     * @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 tBCustomers in body
     */
    @GetMapping("/tb-customers")
    @Timed
    public ResponseEntity<List<TBCustomerDTO>> getAllTBCustomers(TBCustomerCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBCustomers by criteria: {}", criteria);
        Page<TBCustomerDTO> page = tBCustomerQueryService.findByCriteria(criteria, pageable);
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-customers");
        return ResponseEntity.ok().headers(headers).body(page.getContent());
    }

    /**
     * GET  /tb-customers : get all the tBCustomers.
     *
     * @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 tBCustomers in body
     */
    @GetMapping("/tb-customers-dropdown-list/{roleId}")
    @Timed
    public ResponseEntity<List<TBCustomerDTO>> getAllTBCustomersByRoleId(@PathVariable Long roleId,TBCustomerCriteria criteria, Pageable pageable) {
        log.debug("REST request to get TBCustomers by criteria: {}", criteria);
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        TBRoleDTO roleDTO = tbRoleService.findOne(roleId).get();

        Page<TBCustomerDTO> page = tBCustomerQueryService.findByCriteria(criteria, pageable);
        List<TBCustomerDTO> result = page.getContent();
        if(currentUser.getCustomerId() != null){
            result = page.getContent().stream()
                .filter(item -> item.getId().equals(currentUser.getCustomerId()))
                    .collect(Collectors.toList());
        } else {
            if (!roleDTO.getIsAllCustomer()) {
                result = page.getContent().stream()
                    .filter(item -> item.getId().equals(roleDTO.getTbCustomerId()))
                    .collect(Collectors.toList());
            }
        }
        HttpHeaders headers = PaginationUtil.generatePaginationHttpHeaders(page, "/api/tb-customers-dropdown-list");
        return ResponseEntity.ok().headers(headers).body(result);
    }

    /**
    * GET  /tb-customers/count : count all the tBCustomers.
    *
    * @param criteria the criterias which the requested entities should match
    * @return the ResponseEntity with status 200 (OK) and the count in body
    */
    @GetMapping("/tb-customers/count")
    @Timed
    public ResponseEntity<Long> countTBCustomers(TBCustomerCriteria criteria) {
        log.debug("REST request to count TBCustomers by criteria: {}", criteria);
        return ResponseEntity.ok().body(tBCustomerQueryService.countByCriteria(criteria));
    }

    /**
     * GET  /tb-customers/:id : get the "id" tBCustomer.
     *
     * @param id the id of the tBCustomerDTO to retrieve
     * @return the ResponseEntity with status 200 (OK) and with body the tBCustomerDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-customers/{id}")
    @Timed
    public ResponseEntity<TBCustomerDTO> getTBCustomer(@PathVariable Long id) {
        log.debug("REST request to get TBCustomer : {}", id);
        Optional<TBCustomerDTO> tBCustomerDTO = tBCustomerService.findOne(id);
        return ResponseUtil.wrapOrNotFound(tBCustomerDTO);
    }

    /**
     * GET  /tb-customers-current-user/
     *
     * @return the ResponseEntity with status 200 (OK) and with body the tBCustomerDTO, or with status 404 (Not Found)
     */
    @GetMapping("/tb-customers-current-user")
    @Timed
    public ResponseEntity<TBCustomerDTO> getTBCustomerByCurrentUser() {

        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if(currentUser.getCustomerId() != null) {
            Optional<TBCustomerDTO> tBCustomerDTO = tBCustomerService.findOne(currentUser.getCustomerId());
            return ResponseUtil.wrapOrNotFound(tBCustomerDTO);
        }
        return null;
    }

    /**
     * DELETE  /tb-customers/:id : delete the "id" tBCustomer.
     *
     * @param id the id of the tBCustomerDTO to delete
     * @return the ResponseEntity with status 200 (OK)
     */
    @DeleteMapping("/tb-customers/{id}")
    @Timed
    public ResponseEntity<Void> deleteTBCustomer(@PathVariable Long id) {
        log.debug("REST request to delete TBCustomer : {}", id);
        tBCustomerService.delete(id);
        return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build();
    }

    /**
     * SEARCH  /_search/tb-customers?query=:query : search for the tBCustomer corresponding
     * to the query.
     *
     * @param query the query of the tBCustomer search
     * @param pageable the pagination information
     * @return the result of the search
     */
    @GetMapping("/_search/tb-customers")
    @Timed
    public ResponseEntity<List<TBCustomerDTO>> searchTBCustomers(@RequestParam String query, @RequestParam String status,  Pageable pageable) {
        log.debug("REST request to search for a page of TBCustomers for query {}", query);
        UserDTO currentUser = userService.getCurrentUserDTO().get();
        if (currentUser.getCustomerId() != null) {
            Page<TBCustomerDTO> page;
            if((query != null &&  !query.isEmpty()) | (status != null &&  !status.isEmpty())) {
                page = tBCustomerQueryService.searchCustomer(query, status, pageable);
            } else {
                page = tBCustomerService.search(query, pageable);
            }
            HttpHeaders headers = PaginationUtil.generateSearchPaginationHttpHeaders(query, page, "/api/_search/tb-customers");
            return ResponseEntity.ok().headers(headers).body(page.getContent());
        }
        return null;
    }

}
