package eu.eudat.controllers;


import eu.eudat.configurations.dynamicgrant.DynamicGrantConfiguration;
import eu.eudat.criteria.DMPCriteria;
import eu.eudat.data.dao.criteria.DynamicFieldsCriteria;
import eu.eudat.data.dao.criteria.RequestItem;
import eu.eudat.data.entities.DMP;
import eu.eudat.data.entities.Dataset;
import eu.eudat.data.query.items.table.datasetprofile.DatasetProfileTableRequestItem;
import eu.eudat.data.query.items.table.dmp.DataManagementPlanTableRequest;
import eu.eudat.data.query.items.table.dmp.DataManagmentPlanPublicTableRequest;
import eu.eudat.exceptions.datamanagementplan.DMPNewVersionException;
import eu.eudat.exceptions.datamanagementplan.DMPWithDatasetsDeleteException;
import eu.eudat.exceptions.security.UnauthorisedException;
import eu.eudat.logic.managers.DataManagementPlanManager;
import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.proxy.config.configloaders.ConfigLoader;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.logic.services.operations.DatabaseRepository;
import eu.eudat.logic.utilities.documents.helpers.FileEnvelope;
import eu.eudat.logic.utilities.documents.pdf.PDFUtils;
import eu.eudat.models.data.datasetprofile.DatasetProfileListingModel;
import eu.eudat.models.data.datasetwizard.DatasetsToBeFinalized;
import eu.eudat.models.data.dmp.DataManagementPlan;
import eu.eudat.models.data.helpermodels.Tuple;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.listingmodels.DataManagementPlanListingModel;
import eu.eudat.models.data.listingmodels.DataManagementPlanOverviewModel;
import eu.eudat.models.data.listingmodels.UserInfoListingModel;
import eu.eudat.models.data.listingmodels.VersionListingModel;
import eu.eudat.models.data.security.Principal;
import eu.eudat.query.DMPQuery;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.activation.MimetypesFileTypeMap;
import javax.validation.Valid;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static org.springframework.http.MediaType.*;


@RestController
@CrossOrigin
@RequestMapping(value = {"/api/dmps/"})
public class DMPs extends BaseController {
    private static final Logger logger = LoggerFactory.getLogger(DMPs.class);

    private DynamicGrantConfiguration dynamicGrantConfiguration;
    private Environment environment;
    private DataManagementPlanManager dataManagementPlanManager;
    private ConfigLoader configLoader;

    @Autowired
    public DMPs(ApiContext apiContext, DynamicGrantConfiguration dynamicGrantConfiguration, Environment environment,
                DataManagementPlanManager dataManagementPlanManager, ConfigLoader configLoader) {
        super(apiContext);
        this.dynamicGrantConfiguration = dynamicGrantConfiguration;
        this.environment = environment;
        this.dataManagementPlanManager = dataManagementPlanManager;
        this.configLoader = configLoader;
    }

    /*
    * Data Retrieval
    * */

    @RequestMapping(method = RequestMethod.POST, value = {"/paged"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DataTableData<DataManagementPlanListingModel>>> getPaged(@Valid @RequestBody DataManagementPlanTableRequest dataManagementPlanTableRequest,
                                                                                         @RequestParam String fieldsGroup,
                                                                                         @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
        DataTableData<DataManagementPlanListingModel> dataTable = this.dataManagementPlanManager.getPaged(dataManagementPlanTableRequest, principal, fieldsGroup);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"{id}"})
    public @ResponseBody
    ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType,
							 @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
        if (contentType.equals("application/xml") || contentType.equals("application/msword")) {
            return this.dataManagementPlanManager.getDocument(id, contentType, principal, this.configLoader);
        } else {
            eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, false, true);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/plain/{id}"})
    public @ResponseBody
    ResponseEntity getSingleNoDatasets(@PathVariable String id, @RequestHeader("Content-Type") String contentType,
                             @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {

        eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, false, false);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));

    }

    @RequestMapping(method = RequestMethod.POST, value = {"/datasetProfilesUsedByDmps/paged"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DataTableData<DatasetProfileListingModel>>> getUsingDatasetProfilesPaged(@RequestBody DatasetProfileTableRequestItem datasetProfileTableRequestItem, Principal principal) {
        DataTableData<DatasetProfileListingModel> datasetProfileTableData = this.dataManagementPlanManager.getDatasetProfilesUsedByDMP(datasetProfileTableRequestItem, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DatasetProfileListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(datasetProfileTableData));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/overview/{id}"})
    public @ResponseBody
    ResponseEntity getOverviewSingle(@PathVariable String id,@ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
        try {
            DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, principal, false);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
        } catch (Exception e) {
            if (e instanceof UnauthorisedException) {
                return ResponseEntity.status(HttpStatus.FORBIDDEN).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
            } else {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.ERROR_MESSAGE));
            }
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"})
    public @ResponseBody
    ResponseEntity getSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
//        try {
        eu.eudat.models.data.dmp.DataManagementPlan dataManagementPlan = this.dataManagementPlanManager.getSingle(id, principal, true, true);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
//        } catch (Exception ex) {
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlan>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
//        }
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/publicOverview/{id}"})
    public @ResponseBody
    ResponseEntity getOverviewSinglePublic(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
//        try {
        DataManagementPlanOverviewModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSingle(id, principal, true);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlan));
//        } catch (Exception ex) {
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
//        }
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/dynamic"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<List<Tuple<String, String>>>> getWithCriteria(@RequestBody RequestItem<DynamicFieldsCriteria> criteriaRequestItem, Principal principal) throws InstantiationException, IllegalAccessException {
        List<Tuple<String, String>> dataTable = this.dataManagementPlanManager.getDynamicFields(criteriaRequestItem.getCriteria().getId(), this.dynamicGrantConfiguration, criteriaRequestItem.getCriteria());
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<Tuple<String, String>>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/versions/{id}"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<List<VersionListingModel>>> getVersions(@PathVariable(value= "id") String groupId, @RequestParam(value= "public") Boolean isPublic,
                                                                     @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws Exception {
        List<VersionListingModel> versions = this.dataManagementPlanManager.getAllVersions(groupId, principal, isPublic);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<VersionListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(versions));
    }

    /*
    * Data Export
    * */

    @RequestMapping(method = RequestMethod.GET, value = {"rda/{id}"})
    public @ResponseBody
    ResponseEntity getRDAJsonDocument(@PathVariable String id, @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) {
    	try {
        return this.dataManagementPlanManager.getRDAJsonDocument(id, principal);
    	} catch (Exception e) {
    		return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseItem<>().message(e.getMessage()).status(ApiMessageCode.ERROR_MESSAGE));
    	}
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
    public @ResponseBody
    ResponseEntity<byte[]> getPDFDocument(@PathVariable String id, @RequestHeader("Content-Type") String contentType,
                                          @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
        FileEnvelope file = this.dataManagementPlanManager.getWordDocument(id, principal, configLoader);
        String name = file.getFilename().substring(0, file.getFilename().length() - 5).replace(" ", "_").replace(",", "_");
        File pdffile = PDFUtils.convertToPDF(file, environment);
        InputStream resource = new FileInputStream(pdffile);
        logger.info("Mime Type of " + name + " is " +
                new MimetypesFileTypeMap().getContentType(file.getFile()));
        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentLength(pdffile.length());
        responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        responseHeaders.set("Content-Disposition", "attachment;filename=" + name + ".pdf");
        responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
        responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");

        byte[] content = org.apache.poi.util.IOUtils.toByteArray(resource);
        resource.close();
        Files.deleteIfExists(file.getFile().toPath());
        Files.deleteIfExists(pdffile.toPath());
        return new ResponseEntity<>(content, responseHeaders, HttpStatus.OK);
    }

    /*
    * Data Management
    * */

    @Transactional
    @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<eu.eudat.models.data.dmp.DataManagementPlan>> createOrUpdate(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception {
        DMP dmp = this.dataManagementPlanManager.createOrUpdate(dataManagementPlanEditorModel, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.models.data.dmp.DataManagementPlan>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(new eu.eudat.models.data.dmp.DataManagementPlan().fromDataModel(dmp)));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.POST, path = "full", consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UUID>> createOrUpdateWithDatasets(@RequestBody eu.eudat.models.data.dmp.DataManagementPlanEditorModel dataManagementPlanEditorModel, Principal principal) throws Exception {
        DMP dmp = this.dataManagementPlanManager.createOrUpdateWithDatasets(dataManagementPlanEditorModel, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(dmp.getId()));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/new/{id}"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UUID>> newVersion(@PathVariable UUID id, @Valid @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
        try {
            UUID result = this.dataManagementPlanManager.newVersion(id, dataManagementPlan, principal);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.NO_MESSAGE).payload(result));
        } catch (DMPNewVersionException exception) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<UUID>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/clone/{id}"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<UUID>> clone(@PathVariable UUID id, @RequestBody eu.eudat.models.data.dmp.DataManagementPlanNewVersionModel dataManagementPlan, Principal principal) throws Exception {
        UUID cloneId = this.dataManagementPlanManager.clone(dataManagementPlan, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<UUID>().status(ApiMessageCode.SUCCESS_MESSAGE).payload(cloneId));
    }

    @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DMP>> delete(@PathVariable UUID id, Principal principal) {
        try {
            this.dataManagementPlanManager.delete(id);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Deleted Datamanagement Plan"));
        } catch (DMPWithDatasetsDeleteException | IOException exception) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message(exception.getMessage()));
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/upload"})
    public ResponseEntity<ResponseItem> dmpUpload(@RequestParam("file") MultipartFile[] files, @RequestParam(name = "profiles", required = false)String[] profiles, Principal principal) throws Exception {
        if (files[0].getContentType().equals(APPLICATION_JSON.toString())) {
            this.dataManagementPlanManager.createFromRDA(files, principal, profiles);
        } else if (files[0].getContentType().equals(APPLICATION_ATOM_XML.toString()) || files[0].getContentType().equals(TEXT_XML.toString())) {
            this.dataManagementPlanManager.createDmpFromXml(files, principal, profiles);
        } else {
            return ResponseEntity.badRequest().body(new ResponseItem().status(ApiMessageCode.ERROR_MESSAGE).message("File format is not supported"));
        }
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List>()
                .status(ApiMessageCode.SUCCESS_MESSAGE));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/makepublic/{id}"})
    public ResponseEntity<ResponseItem<DMP>> makePublic(@PathVariable String id, Principal principal) {
        try {
            this.dataManagementPlanManager.makePublic(UUID.fromString(id), principal);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made public."));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to make Data Management Plan public."));
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/finalize/{id}"})
    public ResponseEntity<ResponseItem<DMP>> makeFinalize(@PathVariable String id, Principal principal, @RequestBody DatasetsToBeFinalized datasetsToBeFinalized) {
        try {
            this.dataManagementPlanManager.makeFinalize(UUID.fromString(id), principal, datasetsToBeFinalized);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made finalized."));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to finalize Data Management Plan."));
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/unfinalize/{id}"})
    public ResponseEntity<ResponseItem<DMP>> undoFinalize(@PathVariable String id, Principal principal) {
        try {
            this.dataManagementPlanManager.undoFinalize(UUID.fromString(id), principal);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Data Datamanagement Plan made active."));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to unfinalize the Data Management Plan."));
        }
    }


    @RequestMapping(method = RequestMethod.POST, value = {"/updateusers/{id}"})
    public ResponseEntity<ResponseItem<DMP>> updateUsers(@PathVariable String id, @RequestBody List<UserInfoListingModel> users, Principal principal) {
        try {
            this.dataManagementPlanManager.updateUsers(UUID.fromString(id), users, principal);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully Updated Colaborators for Data Datamanagement Plan."));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DMP>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to update the users of Data Management Plan."));
        }
    }

    /*
    * DOI Generation
    * */

    @RequestMapping(method = RequestMethod.POST, value = {"/createZenodoDoi/{id}"})
    public ResponseEntity<ResponseItem<String>> createZenodoDoi(@PathVariable String id, Principal principal) {
        try {
            String zenodoDOI = this.dataManagementPlanManager.createZenodoDoi(UUID.fromString(id), principal);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<String>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Successfully created DOI for Data Datamanagement Plan in question.").payload(zenodoDOI));
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<String>().status(ApiMessageCode.ERROR_MESSAGE).message("Failed to create DOI for the Data Management Plan: " + e.getMessage()));
        }
    }

    /*
    * Data Index
    * */

    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = {"/index"})
    public @ResponseBody
    ResponseEntity<ResponseItem<Dataset>> generateIndex(Principal principal) throws Exception {
        this.dataManagementPlanManager.generateIndex(principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Generated").payload(null));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = {"/index"})
    public @ResponseBody
    ResponseEntity<ResponseItem<Dataset>> clearIndex(Principal principal) throws Exception {
        this.dataManagementPlanManager.clearIndex(principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Cleared").payload(null));
    }

    /*
    * Misc
    * */

    @RequestMapping(method = RequestMethod.POST, value = {"/test"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DataTableData<Map>>> test(@RequestBody DMPCriteria criteria, @ClaimedAuthorities(claims = {Authorities.ANONYMOUS}) Principal principal) throws Exception {
        DatabaseRepository dbRepo = this.getApiContext().getOperationsContext().getDatabaseRepository();

        DMPQuery query = criteria.buildQuery(dbRepo);

        List<Map> models = query.getQuery().toListWithFields();
        DataTableData<Map> dmp = new DataTableData<>();
        dmp.setData(models);
        dmp.setTotalCount(query.getQuery().count());
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<Map>>().status(ApiMessageCode.NO_MESSAGE).payload(dmp));
    }

    /*@RequestMapping(method = RequestMethod.POST, value = {"/public/paged"}, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DataTableData<DataManagementPlanListingModel>>> getPublicPaged(@RequestBody DataManagmentPlanPublicTableRequest dmpTableRequest,
                                                                                               @ClaimedAuthorities(claims = {Authorities.ADMIN, Authorities.MANAGER, Authorities.USER, Authorities.ANONYMOUS}) Principal principal,
                                                                                               @RequestParam String fieldsGroup) throws Exception {
        DataTableData<DataManagementPlanListingModel> dmp = this.dataManagementPlanManager.getPublicPaged(dmpTableRequest, fieldsGroup, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dmp));
    }*/
    /*@Transactional
    @RequestMapping(method = RequestMethod.GET, value = {"{id}/unlock"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DMP>> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
        this.dataManagementPlanManager.unlock(id);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DMP>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked"));
    }*/
}
