package eu.eudat.publicapi.controllers;

import eu.eudat.controllers.BaseController;
import eu.eudat.logic.security.claims.ClaimedAuthorities;
import eu.eudat.logic.services.ApiContext;
import eu.eudat.models.data.helpers.common.DataTableData;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.publicapi.managers.DataManagementPlanPublicManager;
import eu.eudat.publicapi.models.listingmodels.DataManagementPlanPublicListingModel;
import eu.eudat.publicapi.models.overviewmodels.DataManagementPlanPublicModel;
import eu.eudat.publicapi.request.dmp.DataManagmentPlanPublicTableRequest;
import eu.eudat.types.ApiMessageCode;
import eu.eudat.types.Authorities;
import io.swagger.annotations.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

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

@Api(tags = "DMPs", description = "Provides DMP public API's.")
@RestController
@CrossOrigin
@RequestMapping(value = {"/api/public/dmps"})
public class PublicDmpsDocumentation extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(PublicDmpsDocumentation.class);

    private DataManagementPlanPublicManager dataManagementPlanManager;

    private static final String getPagedNotes = "The json response is of type **ResponseItem<DataTableData< DataManagementPlanPublicListingModel >>** containing the following properties:\n" +
            "  1. **message**: string, message indicating error, null if everything went well\n" +
            "  2. **statusCode**: integer, status code indicating if something unexpected happened, otherwise 0\n" +
            "  3. **responseType**: integer, 0 for json, 1 for file\n" +
            "  4. **payload**: DataTableData, containing the number of values of actual data returned and the data of type **DataManagementPlanPublicListingModel**\n" +
            "4.1. id: string, id of dmp returned\n" +
            "4.2. label: string, label of dmp\n" +
            "4.3. grant: string, grant of dmp\n" +
            "4.4. createdAt: date, creation time of dmp\n" +
            "4.5. modifiedAt: date, modification time of dmp\n" +
            "4.6. version: integer, version of dmp\n" +
            "4.7. groupId: uuid, group id in which dmp belongs\n" +
            "4.8. users: list of UserInfoPublicModel, user who collaborated on the dmp\n" +
            "4.9. finalizedAt: date, finalization date\n" +
            "4.10. publishedAt: date, publication date\n";
    private static final String getPagedResponseExample = "{\n" +
            "  \"statusCode\": 0,\n" +
            "  \"responseType\": 0,\n" +
            "  \"message\": null,\n" +
            "  \"payload\": {\n" +
            "    \"totalCount\": 2,\n" +
            "    \"data\": [\n" +
            "      {\n" +
            "        \"id\": \"e9a73d77-adfa-4546-974f-4a4a623b53a8\",\n" +
            "        \"label\": \"Giorgos's DMP\",\n" +
            "        \"grant\": \"Novel EOSC services for Emerging Atmosphere, Underwater and Space Challenges\",\n" +
            "        \"createdAt\": 1579077317000,\n" +
            "        \"modifiedAt\": 1586444334000,\n" +
            "        \"version\": 0,\n" +
            "        \"groupId\": \"d949592d-f862-4b31-a43a-f5f70596df5e\",\n" +
            "        \"users\": [],\n" +
            "        \"finalizedAt\": 1586444334000,\n" +
            "        \"publishedAt\": 1586444334000,\n" +
            "        \"hint\": \"dataManagementPlanListingModel\"\n" +
            "      },\n" +
            "      {\n" +
            "        \"id\": \"e27789f1-de35-4b4a-9587-a46d131c366e\",\n" +
            "        \"label\": \"TestH2020Clone3\",\n" +
            "        \"grant\": \"Evaluation of the Benefits of innovative Concepts of laminar nacelle and HTP installed on a business jet configuration\",\n" +
            "        \"createdAt\": 1600774437000,\n" +
            "        \"modifiedAt\": 1600879107000,\n" +
            "        \"version\": 0,\n" +
            "        \"groupId\": \"7b793c17-cb69-41d2-a97d-e8d1b03ddbed\",\n" +
            "        \"users\": [],\n" +
            "        \"finalizedAt\": 1600879107000,\n" +
            "        \"publishedAt\": 1600879107000,\n" +
            "        \"hint\": \"dataManagementPlanListingModel\"\n" +
            "      }\n" +
            "    ]\n" +
            "  }\n" +
            "}";
    private static final String getPagedRequestBodyDescription = "The dmpTableRequest is a DataManagementPlanPublicTableRequest object with the following fields:\n" +
            "• **length**: how many dmps should be fetched *(required)*\n" + "• **offset**: offset of the returned dmps, first time should be 0, then offset += length\n" +
            "• **orderings**: array of strings specifying the order, format:= +string or -string or asc or desc. " +
            "**+** means ascending order. **-** means descending order.\n&nbsp;&nbsp;&nbsp;&nbsp;Available strings are: 1) status, 2) label, 3) publishedAt, 4) created.\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;**asc** equivalent to +label.\n&nbsp;&nbsp;&nbsp;&nbsp;**desc** equivalent to -label.\n" +
            "**criteria**: this is DataManagementPlanPublicCriteria object which applies filters for the dmp returned. More specifically:\n" +
            " 1. periodStart: date, dmps created date greater than periodStart\n" +
            " 2. periodEnd: date, dmps created date less than periodEnd\n" +
            " 3. grants: list of uuids, dmps with the corresponding grants\n" +
            " 4. funders: list of uuids, dmps with the corresponding funders\n" +
            " 5. datasetTemplates: list of uuids, dataset templates which are described in the dmps\n" +
            " 6. dmpOrganisations: list of strings, dmps belonging to these organisations\n" +
            " 7. collaborators: list of uuids, user who collaborated on the creation/modification of dmps\n" +
            " 8. allVersions: boolean, if dmps should be fetched with all their versions\n" +
            " 9. groupIds: list of uuids, in which groups the dmps are\n" +
            "10. like: string, dmps fetched have this string matched in their label or description\n";
    private static final String getPagedRequestParamDescription = "The fieldsGroup is a string which indicates if the returned objects would have all their properties\n" +
            "There are two available values: 1) listing and 2) autocomplete\n" +
            "**listing**: returns objects with all their properties completed\n" +
            "**autocomplete**: returns objects with only id, label, groupId and creationTime assigned";

    private static final String getOverviewSinglePublicNotes = "The json response is of type **ResponseItem< DataManagementPlanPublicModel >** containing the following properties:\n" +
            " 1. **message**: string, message indicating error, null if everything went well\n" +
            " 2. **statusCode**: integer, status code indicating if something unexpected happened, otherwise 0\n" +
            " 3. **responseType**: integer, 0 for json, 1 for file\n" +
            " 4. **payload**: DataManagementPlanPublicModel, dmp returned\n" +
            "4.1. id: string, id of dmp returned\n" +
            "4.2. label: string, label of dmp\n" +
            "4.3. profile: string, profile of dmp\n" +
            "4.4. grant: GrantPublicOverviewModel, grant of dmp\n" +
            "4.5. createdAt: date, creation time of dmp\n" +
            "4.6. modifiedAt: date, modification time of dmp\n" +
            "4.7. finalizedAt: date, finalization date of dmp\n" +
            "4.8. organisations: list of OrganizationPublicModel, organizations in which dmp belongs\n" +
            "4.9. version: integer, version of dmp\n" +
            "4.10. groupId: uuid, group id in which dmp belongs\n" +
            "4.11. datasets: list of DatasetPublicModel, contained datasets\n" +
            "4.12. associatedProfiles: list of AssociatedProfilePublicModel, associated profiles of dmp\n" +
            "4.13. researchers: list of ResearcherPublicModel, researchers involved in dmp\n" +
            "4.14. users: list of UserInfoPublicModel, user who collaborated on the dmp\n" +
            "4.15. description: string, description of dmp\n" +
            "4.16. publishedAt: date, publication date\n" +
            "4.17. doi: string, if dmp has been published to zenodo so it has doi\n";
    private static final String getOverviewSinglePublicResponseExample = "{\n" +
            "  \"statusCode\": 0,\n" +
            "  \"responseType\": 0,\n" +
            "  \"message\": null,\n" +
            "  \"payload\": {\n" +
            "    \"id\": \"e9a73d77-adfa-4546-974f-4a4a623b53a8\",\n" +
            "    \"label\": \"Giorgos's DMP\",\n" +
            "    \"profile\": null,\n" +
            "    \"grant\": {\n" +
            "      \"id\": \"c8309ae5-4e56-43eb-aa5a-9950c24051fe\",\n" +
            "      \"label\": \"Novel EOSC services for Emerging Atmosphere, Underwater and Space Challenges\",\n" +
            "      \"abbreviation\": null,\n" +
            "      \"description\": null,\n" +
            "      \"startDate\": null,\n" +
            "      \"endDate\": null,\n" +
            "      \"uri\": null,\n" +
            "      \"funder\": {\n" +
            "        \"id\": \"25e76828-3539-4c66-9870-0ecea7a4d16e\",\n" +
            "        \"label\": \"European Commission||EC\",\n" +
            "        \"hint\": null\n" +
            "      },\n" +
            "      \"hint\": null\n" +
            "    },\n" +
            "    \"createdAt\": 1579077317000,\n" +
            "    \"modifiedAt\": 1586444334000,\n" +
            "    \"finalizedAt\": 1586444334000,\n" +
            "    \"organisations\": [],\n" +
            "    \"version\": 0,\n" +
            "    \"groupId\": \"d949592d-f862-4b31-a43a-f5f70596df5e\",\n" +
            "    \"datasets\": [\n" +
            "      {\n" +
            "        \"id\": \"853a24c3-def4-4978-985f-92e7fa57ef22\",\n" +
            "        \"label\": \"Giorgos's Dataset Desc\",\n" +
            "        \"reference\": null,\n" +
            "        \"uri\": null,\n" +
            "        \"description\": null,\n" +
            "        \"status\": 1,\n" +
            "        \"createdAt\": 1579077532000,\n" +
            "        \"dmp\": {\n" +
            "          \"id\": \"e9a73d77-adfa-4546-974f-4a4a623b53a8\",\n" +
            "          \"label\": \"Giorgos's DMP\",\n" +
            "          \"grant\": \"Novel EOSC services for Emerging Atmosphere, Underwater and Space Challenges\",\n" +
            "          \"createdAt\": 1579077317000,\n" +
            "          \"modifiedAt\": 1586444334000,\n" +
            "          \"version\": 0,\n" +
            "          \"groupId\": \"d949592d-f862-4b31-a43a-f5f70596df5e\",\n" +
            "          \"users\": [\n" +
            "            {\n" +
            "              \"id\": \"00476b4d-0491-44ca-b2fd-92e695062a48\",\n" +
            "              \"name\": \"OpenDMP OpenDMP\",\n" +
            "              \"role\": 0,\n" +
            "              \"email\": \"opendmpeu@gmail.com\",\n" +
            "              \"hint\": \"UserInfoListingModel\"\n" +
            "            }\n" +
            "          ],\n" +
            "          \"finalizedAt\": 1586444334000,\n" +
            "          \"publishedAt\": 1586444334000,\n" +
            "          \"hint\": \"dataManagementPlanListingModel\"\n" +
            "        },\n" +
            "        \"datasetProfileDefinition\": {\n" +
            "          \"pages\": [...],\n" +
            "          \"rules\": [...],\n" +
            "          \"status\": 0\n" +
            "        },\n" +
            "        \"registries\": [],\n" +
            "        \"services\": [],\n" +
            "        \"dataRepositories\": [],\n" +
            "        \"tags\": null,\n" +
            "        \"externalDatasets\": [],\n" +
            "        \"profile\": {\n" +
            "          \"id\": \"2a6e0835-349e-412c-9fcc-8e1298ce8a5a\",\n" +
            "          \"label\": \"Horizon 2020\",\n" +
            "          \"hint\": null\n" +
            "        },\n" +
            "        \"modifiedAt\": 1579077898000,\n" +
            "        \"hint\": \"datasetOverviewModel\"\n" +
            "      }\n" +
            "    ],\n" +
            "    \"associatedProfiles\": [\n" +
            "      {\n" +
            "        \"id\": \"f41bd794-761d-4fe8-ab67-3a989d982c53\",\n" +
            "        \"label\": \"Swedish Research Council\"\n" +
            "      },\n" +
            "      {\n" +
            "        \"id\": \"2a6e0835-349e-412c-9fcc-8e1298ce8a5a\",\n" +
            "        \"label\": \"Horizon 2020\"\n" +
            "      }\n" +
            "    ],\n" +
            "    \"researchers\": [],\n" +
            "    \"users\": [\n" +
            "      {\n" +
            "        \"id\": \"00476b4d-0491-44ca-b2fd-92e695062a48\",\n" +
            "        \"name\": \"OpenDMP OpenDMP\",\n" +
            "        \"role\": 0,\n" +
            "        \"email\": \"opendmpeu@gmail.com\",\n" +
            "        \"hint\": \"UserInfoListingModel\"\n" +
            "      }\n" +
            "    ],\n" +
            "    \"description\": null,\n" +
            "    \"publishedAt\": 1586444334000,\n" +
            "    \"doi\": \"10.5072/zenodo.522151\",\n" +
            "    \"hint\": \"dataManagementPlanOverviewModel\"\n" +
            "  }\n" +
            "}";

    @Autowired
    public PublicDmpsDocumentation(ApiContext apiContext, DataManagementPlanPublicManager dataManagementPlanManager) {
        super(apiContext);
        this.dataManagementPlanManager = dataManagementPlanManager;
    }

    @ApiOperation(value = "This method is used to get a listing of public dmps.", notes = getPagedNotes)
    @ApiResponses(value = {@ApiResponse(
            code = 200,
            message = "The following example is generated using:\n" +
                    "a) body: *{\"criteria\": {},\"length\": 2,\"offset\": 0,\"orderings\": {\"fields\": []} }*\n" +
                    "b) fieldsGroup: listing",
            examples = @Example({@ExampleProperty(
                    value = getPagedResponseExample,
                    mediaType = APPLICATION_JSON_VALUE
            )})
    )})
    @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DataTableData<DataManagementPlanPublicListingModel>>> getPaged(@Valid @RequestBody @ApiParam(value = getPagedRequestBodyDescription) DataManagmentPlanPublicTableRequest dmpTableRequest,
                                                                                               @RequestParam @ApiParam(value = getPagedRequestParamDescription, example = "listing") String fieldsGroup) throws Exception {
        DataTableData<DataManagementPlanPublicListingModel> dataTable = this.dataManagementPlanManager.getPublicPaged(dmpTableRequest, fieldsGroup);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataTableData<DataManagementPlanPublicListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataTable));
    }

    @ApiOperation(value = "This method is used to get the overview of a public dmp.", notes = getOverviewSinglePublicNotes)
    @ApiResponses(value = {@ApiResponse(
            code = 200,
            message = "The following example is generated using id: *e9a73d77-adfa-4546-974f-4a4a623b53a8*",
            examples = @Example({@ExampleProperty(
                    value = getOverviewSinglePublicResponseExample,
                    mediaType = APPLICATION_JSON_VALUE
            )})
    )})
    @RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DataManagementPlanPublicModel>> getOverviewSinglePublic(@PathVariable @ApiParam(value = "fetch the dmp with the given id", example = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") String id) throws Exception {
//        try {
        DataManagementPlanPublicModel dataManagementPlan = this.dataManagementPlanManager.getOverviewSinglePublic(id);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DataManagementPlanPublicModel>().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()));
//        }
    }

}
