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.DatasetPublicManager;
import eu.eudat.publicapi.models.listingmodels.DatasetPublicListingModel;
import eu.eudat.publicapi.models.overviewmodels.DatasetPublicModel;
import eu.eudat.publicapi.request.dataset.DatasetPublicTableRequest;
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 static org.springframework.http.MediaType.APPLICATION_JSON_VALUE;

@Api(tags = "Datasets Description", description = "Provides Dataset description public API's.")
@RestController
@CrossOrigin
@RequestMapping(value = {"/api/public/datasets/"})
public class PublicDatasetsDescriptionDocumentation extends BaseController {

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

    private DatasetPublicManager datasetManager;

    public static final String getPagedNotes = "The json response is of type **ResponseItem<DataTableData< DatasetPublicListingModel >>** 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 **DatasetPublicListingModel**\n" +
            "4.1. id: string, id of dataset returned\n" +
            "4.2. label: string, label of dataset\n" +
            "4.3. grant: string, grant of dataset\n" +
            "4.4. dmp: string, dmp description\n" +
            "4.5. dmpId: string, dmp's id\n" +
            "4.6. profile: DatasetProfilePublicModel, dataset's profile\n" +
            "4.8. createdAt: date, creation date\n" +
            "4.9. modifiedAt: date, modification date\n" +
            "4.10. description: string, dataset's description\n" +
            "4.11. finalizedAt: date, finalization date\n" +
            "4.12. dmpPublishedAt: date, dmp's publication date\n" +
            "4.13. version: integer, dataset's version\n" +
            "4.14. users: list of UserInfoPublicModel, user who collaborated on the dataset\n";
    public static final String getPagedResponseExample = "{\n" +
            "  \"statusCode\": 0,\n" +
            "  \"responseType\": 0,\n" +
            "  \"message\": null,\n" +
            "  \"payload\": {\n" +
            "    \"totalCount\": 2,\n" +
            "    \"data\": [\n" +
            "      {\n" +
            "        \"id\": \"ef7dfbdc-c5c1-46a7-a37b-c8d8692f1c0e\",\n" +
            "        \"label\": \"BARKAMOL RIVOJLANGAN SHAXSNI TARBIYALASHDA  HARAKATLI O`YINLARNING O`RNI\",\n" +
            "        \"grant\": \"A next generation nano media tailored to capture and recycle hazardous micropollutants in contaminated industrial wastewater.\",\n" +
            "        \"dmp\": \"test for demo\",\n" +
            "        \"dmpId\": \"9dee6e72-7a4c-4fbd-b8a4-1f8cda38eb5e\",\n" +
            "        \"profile\": {\n" +
            "          \"id\": \"771283d7-a5be-4a93-bd3c-8b1883fe837c\",\n" +
            "          \"label\": \"Horizon Europe\",\n" +
            "          \"hint\": null\n" +
            "        },\n" +
            "        \"createdAt\": 1662711279000,\n" +
            "        \"modifiedAt\": 1662712928000,\n" +
            "        \"description\": \"<p>&nbsp; &nbsp; &nbsp;Annotatsiya &nbsp;Maqolada &nbsp;bolalarni &nbsp;o`yin &nbsp;mavjud &nbsp;bo`lgan &nbsp;shakllarda &nbsp;mavjud&nbsp;<br>\\nhayot &nbsp;bilan &nbsp;kengroq &nbsp;tanishtirishga &nbsp;imkon &nbsp;beradi. &nbsp;O`yin &nbsp;bolalarning &nbsp;turli &nbsp;xil&nbsp;<br>\\nfaoliyati,o`yin &nbsp;ko`nikmalarini &nbsp;shakllantirishga &nbsp;yordam &nbsp;beradi.Ularni &nbsp;fikrlash, &nbsp;his-<br>\\ntuyg`ular, tajribalar, o`yin muammosini hal qilishning faol usullarini izlash, ularning&nbsp;<br>\\no`yin sharoitlari va sharoitlariga bo`ysunishi, o`yindagi bolalarning munosabatlari,&nbsp;<br>\\no`yin orqali bola organik rivojlanadi, &nbsp;inson madaniyatining muhim qatlami kattalar&nbsp;<br>\\no`rtasidagi &nbsp;munosabatlar &nbsp;- &nbsp;oilada, &nbsp;ularning &nbsp;kasbiy &nbsp;faoliyati &nbsp;va &nbsp;boshqalar. &nbsp;O`yin&nbsp;<br>\\no`qituvchilar barcha ta&rsquo;lim vazifalarini, shu jumladan o`rganishni hal qiladigan eng&nbsp;<br>\\nmuhim faoliyat sifatida foydalaniladi.&nbsp;</p>\",\n" +
            "        \"finalizedAt\": 1662712928000,\n" +
            "        \"dmpPublishedAt\": 1662713226000,\n" +
            "        \"version\": 0,\n" +
            "        \"users\": [\n" +
            "          {\n" +
            "            \"id\": \"33024e48-d528-45a5-8035-ea48641bd2f2\",\n" +
            "            \"name\": \"DMP author\",\n" +
            "            \"role\": 0,\n" +
            "            \"email\": \"kanavou.p@gmail.com\",\n" +
            "            \"hint\": \"UserInfoListingModel\"\n" +
            "          }\n" +
            "        ],\n" +
            "        \"hint\": \"datasetListingModel\"\n" +
            "      },\n" +
            "      {\n" +
            "        \"id\": \"0f253ab2-18cb-4798-adc1-135b81cfad0c\",\n" +
            "        \"label\": \"A \\\"zoom-elit\\\" és a kamionosok küzdelme, avagy a meritokrácia és a populizmus összecsapása\",\n" +
            "        \"grant\": \"Discovery Projects - Grant ID: DP140100157\",\n" +
            "        \"dmp\": \"TEST UPDATE 2.8.2022\",\n" +
            "        \"dmpId\": \"1f4daa8f-4e2f-4dc9-a60b-f6b75d313400\",\n" +
            "        \"profile\": {\n" +
            "          \"id\": \"3d43ba45-25fa-4815-81b4-9bf22ecd8316\",\n" +
            "          \"label\": \"HE_Final\",\n" +
            "          \"hint\": null\n" +
            "        },\n" +
            "        \"createdAt\": 1659392761000,\n" +
            "        \"modifiedAt\": 1659393655000,\n" +
            "        \"description\": \"<p>A kanadai kamionosok &bdquo;szabads&aacute;gmenete&rdquo; kapcs&aacute;n a&nbsp;New York Times&nbsp;has&aacute;bjain Ross Donthat publicista egy r&eacute;gi k&ouml;nyvre h&iacute;vja fel a figyelmet, amely sok &eacute;vtizeddel ezelőtt megj&oacute;solta az elit elleni hasonl&oacute; l&aacute;zad&aacute;sokat.</p>\",\n" +
            "        \"finalizedAt\": 1659393654000,\n" +
            "        \"dmpPublishedAt\": 1659393698000,\n" +
            "        \"version\": 0,\n" +
            "        \"users\": [\n" +
            "          {\n" +
            "            \"id\": \"33024e48-d528-45a5-8035-ea48641bd2f2\",\n" +
            "            \"name\": \"DMP author\",\n" +
            "            \"role\": 0,\n" +
            "            \"email\": \"kanavou.p@gmail.com\",\n" +
            "            \"hint\": \"UserInfoListingModel\"\n" +
            "          }\n" +
            "        ],\n" +
            "        \"hint\": \"datasetListingModel\"\n" +
            "      }\n" +
            "    ]\n" +
            "  }\n" +
            "}";
    public static final String getPagedRequestBodyDescription = "The datasetTableRequest is a DatasetPublicTableRequest object with the following fields:\n" +
            "• **length**: how many datasets should be fetched *(required)*\n" + "• **offset**: offset of the returned datasets, 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) created.\n" +
            "&nbsp;&nbsp;&nbsp;&nbsp;**asc** equivalent to +label.\n&nbsp;&nbsp;&nbsp;&nbsp;**desc** equivalent to -label.\n" +
            "**criteria**: this is DatasetPublicCriteria object which applies filters for the datasets returned. More specifically:\n" +
            " 1. periodStart: date, datasets created date greater than periodStart\n" +
            " 2. periodEnd: date, datasets created date less than periodEnd\n" +
            " 3. grants: list of uuids, dmps(datasets) with the corresponding grants\n" +
            " 4. collaborators: list of uuids, user who collaborated on the creation/modification of datasets\n" +
            " 5. datasetTemplates: list of uuids, dataset templates uuids to be included\n" +
            " 6. dmpOrganisations: list of strings, datasets involved in dmps which belong to these organisations\n" +
            " 7. tags: list of Tag objects, tags involved in datasets\n" +
            " 8. dmpIds: list of uuids, dmps with the specific ids\n" +
            " 9. groupIds: list of uuids, in which groups the datasets are\n" +
            "10. allVersions: boolean, if datasets should be fetched with all their versions\n" +
            "11. like: string, datasets fetched have this string matched in their label or description\n";

    public static final String getOverviewSinglePublicNotes = "The json response is of type **ResponseItem< DatasetPublicModel >** 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**: DatasetPublicModel, dmp returned\n" +
            "4.1. id: uuid, id of dataset returned\n" +
            "4.2. label: string, label of dataset\n" +
            "4.3. reference: string, reference of dataset\n" +
            "4.4. uri: string, uri of dataset\n" +
            "4.5. description: string, dataset's description\n" +
            "4.6. status: string, dataset's status\n" +
            "4.7. createdAt: date, creation time of dataset\n" +
            "4.8. dmp: DataManagementPlanPublicListingModel, dmp to which dataset belongs\n" +
            "4.9. datasetProfileDefinition: PagedDatasetProfile, dataset's paged description\n" +
            "4.10. registries: list of RegistryPublicModel, dataset's registries\n" +
            "4.11. services: list of ServicePublicModel, dataset's services\n" +
            "4.12. dataRepositories: list of DataRepositoryPublicModel, dataset's data repositories\n" +
            "4.13. tags: list of Tag, dataset's tags\n" +
            "4.14. externalDatasets: list of ExternalDatasetPublicListingModel, dataset's external datasets\n" +
            "4.15. profile: DatasetProfilePublicModel, dataset's profile\n" +
            "4.16. modifiedAt: date, modification time of dataset\n";
    public static final String getOverviewSinglePublicResponseExample = "{\n" +
            "  \"statusCode\": 0,\n" +
            "  \"responseType\": 0,\n" +
            "  \"message\": null,\n" +
            "  \"payload\": {\n" +
            "    \"id\": \"ef7dfbdc-c5c1-46a7-a37b-c8d8692f1c0e\",\n" +
            "    \"label\": \"BARKAMOL RIVOJLANGAN SHAXSNI TARBIYALASHDA  HARAKATLI O`YINLARNING O`RNI\",\n" +
            "    \"reference\": null,\n" +
            "    \"uri\": null,\n" +
            "    \"description\": \"<p>&nbsp; &nbsp; &nbsp;Annotatsiya &nbsp;Maqolada &nbsp;bolalarni &nbsp;o`yin &nbsp;mavjud &nbsp;bo`lgan &nbsp;shakllarda &nbsp;mavjud&nbsp;<br>\\nhayot &nbsp;bilan &nbsp;kengroq &nbsp;tanishtirishga &nbsp;imkon &nbsp;beradi. &nbsp;O`yin &nbsp;bolalarning &nbsp;turli &nbsp;xil&nbsp;<br>\\nfaoliyati,o`yin &nbsp;ko`nikmalarini &nbsp;shakllantirishga &nbsp;yordam &nbsp;beradi.Ularni &nbsp;fikrlash, &nbsp;his-<br>\\ntuyg`ular, tajribalar, o`yin muammosini hal qilishning faol usullarini izlash, ularning&nbsp;<br>\\no`yin sharoitlari va sharoitlariga bo`ysunishi, o`yindagi bolalarning munosabatlari,&nbsp;<br>\\no`yin orqali bola organik rivojlanadi, &nbsp;inson madaniyatining muhim qatlami kattalar&nbsp;<br>\\no`rtasidagi &nbsp;munosabatlar &nbsp;- &nbsp;oilada, &nbsp;ularning &nbsp;kasbiy &nbsp;faoliyati &nbsp;va &nbsp;boshqalar. &nbsp;O`yin&nbsp;<br>\\no`qituvchilar barcha ta&rsquo;lim vazifalarini, shu jumladan o`rganishni hal qiladigan eng&nbsp;<br>\\nmuhim faoliyat sifatida foydalaniladi.&nbsp;</p>\",\n" +
            "    \"status\": 1,\n" +
            "    \"createdAt\": 1662711279000,\n" +
            "    \"dmp\": {\n" +
            "      \"id\": \"9dee6e72-7a4c-4fbd-b8a4-1f8cda38eb5e\",\n" +
            "      \"label\": \"test for demo\",\n" +
            "      \"grant\": \"A next generation nano media tailored to capture and recycle hazardous micropollutants in contaminated industrial wastewater.\",\n" +
            "      \"createdAt\": 1662710691000,\n" +
            "      \"modifiedAt\": 1662713226000,\n" +
            "      \"version\": 0,\n" +
            "      \"groupId\": \"adaa4e17-7375-45b8-b052-09edaeb6da86\",\n" +
            "      \"users\": [\n" +
            "        {\n" +
            "          \"id\": \"33024e48-d528-45a5-8035-ea48641bd2f2\",\n" +
            "          \"name\": \"DMP author\",\n" +
            "          \"role\": 0,\n" +
            "          \"email\": \"kanavou.p@gmail.com\",\n" +
            "          \"hint\": \"UserInfoListingModel\"\n" +
            "        }\n" +
            "      ],\n" +
            "      \"finalizedAt\": 1662713226000,\n" +
            "      \"publishedAt\": 1662713226000,\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\": \"771283d7-a5be-4a93-bd3c-8b1883fe837c\",\n" +
            "      \"label\": \"Horizon Europe\",\n" +
            "      \"hint\": null\n" +
            "    },\n" +
            "    \"modifiedAt\": 1662712928000,\n" +
            "    \"hint\": \"datasetOverviewModel\"\n" +
            "  }\n" +
            "}";

    @Autowired
    public PublicDatasetsDescriptionDocumentation(ApiContext apiContext, DatasetPublicManager datasetManager) {
        super(apiContext);
        this.datasetManager = datasetManager;
    }

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

    @ApiOperation(value = "This method is used to get the overview of a public dataset.", notes = getOverviewSinglePublicNotes)
    @ApiResponses(value = {@ApiResponse(
            code = 200,
            message = "The following example is generated using id: *ef7dfbdc-c5c1-46a7-a37b-c8d8692f1c0e*",
            examples = @Example({@ExampleProperty(
                    value = getOverviewSinglePublicResponseExample,
                    mediaType = APPLICATION_JSON_VALUE
            )})
    )})
    @RequestMapping(method = RequestMethod.GET, value = {"/{id}"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<DatasetPublicModel>> getOverviewSinglePublic(@PathVariable @ApiParam(value = "fetch the dataset with the given id", example = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx") String id) throws Exception {
//        try {
        DatasetPublicModel dataset = this.datasetManager.getOverviewSinglePublic(id);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetPublicModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
//        } catch (Exception ex) {
//            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DataManagementPlanOverviewModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
//        }
    }
}
