ActionController.java

/*
 * Copyright 2021 Global Crop Diversity Trust
 *
 * 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 org.gringlobal.api.v1;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

import org.apache.commons.lang3.ArrayUtils;
import org.gringlobal.model.AbstractAction;
import org.gringlobal.service.ActionService;
import org.gringlobal.service.ActionService.ActionRequest;
import org.gringlobal.service.ActionService.ActionScheduleFilter;
import org.gringlobal.service.ActionService.ActionScheduleOverview;
import org.gringlobal.service.ShortFilterService;
import org.gringlobal.service.filter.ActionFilter;
import org.springdoc.api.annotations.ParameterObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.http.MediaType;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;

import com.querydsl.core.types.OrderSpecifier;

import io.swagger.v3.oas.annotations.Operation;

/**
 * A basic API controller for action operations
 *
 * @param <T> the entity type
 * @param <F> the action filter
 * @param <R> the action request
 * @param <S> the action service
 */
@Validated
public abstract class ActionController<T extends AbstractAction<T>, F extends ActionFilter<F, T>, R extends ActionRequest, ASF extends ActionScheduleFilter<ASF, T>, S extends ActionService<T, F, R, ASF>>
		extends ApiBaseController {

	protected static final int MAX_PAGE_SIZE = 100;
	protected static final int FILTER_GENERIC_INDEX = 1;
	protected static final int SCHEDULE_FILTER_GENERIC_INDEX = 3;

	@Autowired
	protected S actionService;

	@Autowired
	private ShortFilterService shortFilterService;

	@SuppressWarnings("unchecked")
	private final Class<ASF> actionScheduleFilterType = (Class<ASF>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[SCHEDULE_FILTER_GENERIC_INDEX];

	public ActionController() {
		super();
	}

	@PostMapping(value = "/action/schedule", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "startActions", description = "Start entity actions", summary = "Start actions")
	public List<T> scheduleActions(@RequestBody @Valid final R request) {
		return actionService.scheduleAction(request);
	}

	@PostMapping(value = "/action/start", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "startActions", description = "Start entity actions", summary = "Start actions", deprecated = true)
	public List<T> startActions(@RequestBody @Valid final R request) {
		return actionService.startAction(request);
	}

	@PostMapping(value = "/action/complete", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "completeActions", description = "Complete entity actions", summary = "Complete actions", deprecated = true)
	public List<T> completeActions(@RequestBody @Valid final R request) {
		return actionService.completeAction(request);
	}

	@PostMapping(value = "/action/reopen", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "reopenActions", description = "Reopen entity actions", summary = "Reopen actions", deprecated = true)
	public List<T> reopenActions(@RequestBody @Valid final R request) {
		return actionService.reopenAction(request);
	}

	@PostMapping(value = "/action/list", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "listActions", description = "List actions matching the filter", summary = "List actions by filter")
	public FilteredPage<T, F> listActions(@ParameterObject final Pagination page, @RequestBody(required = false) final F filter) throws IOException {
		var normalizedFilter = shortFilterService.normalizeFilter(filter, filterType());
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, actionService.listActions(normalizedFilter, pageable));
	}

	@PostMapping(value = "/action/list/completed", produces = { MediaType.APPLICATION_JSON_VALUE })
	public FilteredPage<T, ASF> listCompletedActions(@ParameterObject final Pagination page, @RequestBody final ASF filter) throws IOException {
		var normalizedFilter = (ASF) shortFilterService.normalizeFilter(filter, actionScheduleFilterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, actionService.listCompletedActions(filter, pageable));
	}

	@PostMapping(value = "/action/list/canceled", produces = { MediaType.APPLICATION_JSON_VALUE })
	public FilteredPage<T, ASF> listCanceledActions(@ParameterObject final Pagination page, @RequestBody final ASF filter) throws IOException {
		var normalizedFilter = (ASF) shortFilterService.normalizeFilter(filter, actionScheduleFilterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, actionService.listCanceledActions(filter, pageable));
	}

	@PostMapping(value = "/action/list/inProgress", produces = { MediaType.APPLICATION_JSON_VALUE })
	public FilteredPage<T, ASF> listInProgressActions(@ParameterObject final Pagination page, @RequestBody final ASF filter) throws IOException {
		var normalizedFilter = (ASF) shortFilterService.normalizeFilter(filter, actionScheduleFilterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, actionService.listInProgressActions(filter, pageable));
	}

	@PostMapping(value = "/action/list/scheduled", produces = { MediaType.APPLICATION_JSON_VALUE })
	public FilteredPage<T, ASF> listScheduledActions(@ParameterObject final Pagination page, @RequestBody final ASF filter) throws IOException {
		var normalizedFilter = (ASF) shortFilterService.normalizeFilter(filter, actionScheduleFilterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, actionService.listScheduledActions(filter, pageable));
	}

	@PostMapping(value = "/action/list/added", produces = { MediaType.APPLICATION_JSON_VALUE })
	public FilteredPage<T, ASF> listAddedActions(@ParameterObject final Pagination page, @RequestBody final ASF filter) throws IOException {
		var normalizedFilter = (ASF) shortFilterService.normalizeFilter(filter, actionScheduleFilterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, actionService.listAddedActions(filter, pageable));
	}

	@PostMapping(value = "/action/list/created", produces = { MediaType.APPLICATION_JSON_VALUE })
	public FilteredPage<T, ASF> listCreatedActions(@ParameterObject final Pagination page, @RequestBody final ASF filter) throws IOException {
		var normalizedFilter = (ASF) shortFilterService.normalizeFilter(filter, actionScheduleFilterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, actionService.listCreatedActions(filter, pageable));
	}

	@PostMapping(value = "/action/list/overdue", produces = { MediaType.APPLICATION_JSON_VALUE })
	public FilteredPage<T, ASF> listOverdueActions(@ParameterObject final Pagination page, @RequestBody final ASF filter) throws IOException {
		var normalizedFilter = (ASF) shortFilterService.normalizeFilter(filter, actionScheduleFilterType);
		Pageable pageable = ArrayUtils.isEmpty(page.getS()) ? page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE, defaultSort()) : page.toPageRequest(MAX_PAGE_SIZE, DEFAULT_PAGE_SIZE);
		return new FilteredPage<>(normalizedFilter, actionService.listOverdueActions(filter, pageable));
	}

	@PostMapping("/schedule")
	public ActionScheduleOverview actionSchedule(@RequestBody final ASF filter) {
		return actionService.actionScheduleOverview(filter);
	}

	/**
	 * Get entity by id
	 *
	 * @param id the id
	 * @return the loaded record
	 */
	@GetMapping(value = "/action/{id}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "get", description = "Get record by ID", summary = "Get")
	public T get(@PathVariable("id") final long id) {
		return actionService.load(id);
	}

	/**
	 * Remove the entity.
	 *
	 * @param id the id
	 * @return the removed record
	 */
	@DeleteMapping(value = "/action/{id}", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "remove", description = "Delete existing record by ID", summary = "Delete")
	public T remove(@PathVariable("id") final long id) {
		return actionService.remove(actionService.load(id));
	}

	/**
	 * Register a new entity.
	 *
	 * @param entity the site
	 * @return the recorded record
	 */
	@PostMapping(value = "/action", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "create", description = "Create a record", summary = "Add")
	public T create(@RequestBody @Valid @NotNull final T entity) {
		return actionService.load(actionService.create(entity).getId());
	}

	/**
	 * Register several new actions.
	 *
	 * @param inserts list of entities to add
	 * @return insert results
	 */
	@PostMapping(value = "/action/many", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "createMany", description = "Create multiple new actions", summary = "Add many")
	public MultiOp<T> createMany(@RequestBody @Valid @NotNull final List<T> inserts) {
		return actionService.create(inserts);
	}

	/**
	 * Update several actions.
	 *
	 * @param updates list of records to update
	 * @return update results
	 */
	@PutMapping(value = "/action/many", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "updateMany", description = "Update multiple actions", summary = "Update many")
	public MultiOp<T> updateMany(@RequestBody @Valid @NotNull final List<T> updates) {
		return actionService.updateFast(updates);
	}

	/**
	 * Update the entity.
	 *
	 * @param entity entity with updates
	 * @return the updated record
	 */
	@PutMapping(value = "/action", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "update", description = "Update an existing record", summary = "Update")
	public T update(@RequestBody @Valid @NotNull final T entity) {
		return actionService.load(actionService.update(entity).getId());
	}

	/**
	 * Assign actions to sids.
	 *
	 * @param actionAssignee map of action ids and sid ids
	 * @return the assigned actions
	 */
	@PostMapping(value = "/action/assign", produces = { MediaType.APPLICATION_JSON_VALUE })
	@Operation(operationId = "assignActions", description = "Assign actions to sids", summary = "Assign actions")
	public List<T> assignActions(@RequestBody @Valid @NotNull final Map<Long, String> actionAssignee) {
		return actionService.assignActions(actionAssignee);
	}

	/**
	 * Default order specifier for this entity.
	 *
	 * @return the order specifier
	 */
	protected OrderSpecifier<?>[] defaultSort() {
		return null;
	}

	/**
	 * Filter type
	 *
	 * @return the class
	 */
	@SuppressWarnings("unchecked")
	protected Class<F> filterType() {
		return (Class<F>)((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[FILTER_GENERIC_INDEX];
	}

}