<%#
 Copyright 2013-2020 the original author or authors from the BegCode project.

 This file is part of the JHipster project, see https://www.jhipster.tech/
 for more information.

 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
-%>
package <%= packageName %>.web.rest;

<%_
const pageName = ormTool !== 'mybatis' ? 'Page': 'IPage';
const pageType = ormTool !== 'mybatis' ? 'Pageable': 'IPage';
const pageGetContent = ormTool !== 'mybatis' ? 'getContent': 'getRecords';
const pageUtil = ormTool !== 'mybatis' ? 'PaginationUtil': 'IPageUtil';
_%>
import <%= packageName %>.service.AuditEventService;

<%_ if (!reactive) { _%>
import tech.jhipster.web.util.ResponseUtil;
<%_ } _%>
<%_ if (ormTool !== 'mybatis') { _%>
import org.springframework.data.domain.Page<% if (reactive) { %>Impl<% } %>;
import org.springframework.data.domain.Pageable;
import tech.jhipster.web.util.PaginationUtil;
<%_ } else { _%>
import <%= packageName %>.util.web.IPageUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
<%_ } _%>
import org.springframework.boot.actuate.audit.AuditEvent;
<%_ if (!reactive) { _%>
import org.springframework.http.HttpHeaders;
<%_ } _%>
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
<%_ if (reactive) { _%>
import org.springframework.http.server.reactive.ServerHttpRequest;
<%_ } _%>
import org.springframework.web.bind.annotation.*;
<%_ if (!reactive) { _%>
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
<%_ } else { _%>
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
<%_ } _%>

import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
<%_ if (reactive) { _%>
import java.util.ArrayList;
<%_ } _%>
<%_ if (!reactive) { _%>
import java.util.List;
<%_ } _%>

/**
 * REST controller for getting the {@link AuditEvent}s.
 */
@RestController
@RequestMapping("/management/audits")
public class AuditResource {

    private final AuditEventService auditEventService;

    public AuditResource(AuditEventService auditEventService) {
        this.auditEventService = auditEventService;
    }

    /**
     * {@code GET /audits} : get a page of {@link AuditEvent}s.
     *
    <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
    <%_ } _%>
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent}s in body.
     */
    @GetMapping
    <%_ if (!reactive) { _%>
    public ResponseEntity<List<AuditEvent>> getAll(<%- pageType%> pageable) {
        <%= pageName%><AuditEvent> page = auditEventService.findAll(pageable);
        HttpHeaders headers = <%= pageUtil%>.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return new ResponseEntity<>(page.<%= pageGetContent%>(), headers, HttpStatus.OK);
    <%_ } else { _%>
    public Mono<ResponseEntity<Flux<AuditEvent>>> getAll(ServerHttpRequest request, Pageable pageable) {
        return auditEventService.count()
            .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total))
            .map(page -> PaginationUtil.generatePaginationHttpHeaders(UriComponentsBuilder.fromHttpRequest(request), page))
            .map(headers -> ResponseEntity.ok().headers(headers).body(auditEventService.findAll(pageable)));
    <%_ } _%>
    }

    /**
     * {@code GET  /audits} : get a page of {@link AuditEvent} between the {@code fromDate} and {@code toDate}.
     *
     * @param fromDate the start of the time period of {@link AuditEvent} to get.
     * @param toDate the end of the time period of {@link AuditEvent} to get.
    <%_ if (reactive) { _%>
     * @param request a {@link ServerHttpRequest} request.
    <%_ } _%>
     * @param pageable the pagination information.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the list of {@link AuditEvent} in body.
     */
    @GetMapping(params = {"fromDate", "toDate"})
    public <% if (!reactive) { %>ResponseEntity<List<AuditEvent>><% } else { %>Mono<ResponseEntity<Flux<AuditEvent>>><% } %> getByDates(
        @RequestParam(value = "fromDate") LocalDate fromDate,
        @RequestParam(value = "toDate") LocalDate toDate,
        <%_ if (reactive) { _%>
        ServerHttpRequest request,
        <%_ } _%>
        <%- pageType%> pageable) {

        Instant from = fromDate.atStartOfDay(ZoneId.systemDefault()).toInstant();
        Instant to = toDate.atStartOfDay(ZoneId.systemDefault()).plusDays(1).toInstant();

        <%_ if (!reactive) { _%>
        <%= pageName%><AuditEvent> page = auditEventService.findByDates(from, to, pageable);
        HttpHeaders headers = <%= pageUtil%>.generatePaginationHttpHeaders(ServletUriComponentsBuilder.fromCurrentRequest(), page);
        return new ResponseEntity<>(page.<%= pageGetContent%>(), headers, HttpStatus.OK);
        <%_ } else { _%>
        Flux<AuditEvent> events = auditEventService.findByDates(from, to, pageable);
        return auditEventService.countByDates(from, to)
            .map(total -> new PageImpl<>(new ArrayList<>(), pageable, total))
            .map(page -> PaginationUtil.generatePaginationHttpHeaders(UriComponentsBuilder.fromHttpRequest(request), page))
            .map(headers -> ResponseEntity.ok().headers(headers).body(events));
        <%_ } _%>
    }

    /**
     * {@code GET  /audits/:id} : get an {@link AuditEvent} by id.
     *
     * @param id the id of the entity to get.
     * @return the {@link ResponseEntity} with status {@code 200 (OK)} and the {@link AuditEvent} in body, or status {@code 404 (Not Found)}.
     */
    @GetMapping("/{id:.+}")
    <%_ if (!reactive) { _%>
    public ResponseEntity<AuditEvent> get(@PathVariable <%= pkType %> id) {
        return ResponseUtil.wrapOrNotFound(auditEventService.find(id));
    <%_ } else { _%>
    public Mono<AuditEvent> get(@PathVariable <%= pkType %> id) {
        return auditEventService.find(id)
            .switchIfEmpty(Mono.error(new ResponseStatusException(HttpStatus.NOT_FOUND)));
    <%_ } _%>
    }
}
