package eu.eudat.controllers;

import eu.eudat.data.entities.Dataset;
import eu.eudat.data.query.items.item.dataset.DatasetWizardAutocompleteRequest;
import eu.eudat.data.query.items.item.datasetprofile.DatasetProfileWizardAutocompleteRequest;
import eu.eudat.exceptions.datasetwizard.DatasetWizardCannotUnlockException;
import eu.eudat.logic.managers.DatasetManager;
import eu.eudat.logic.managers.DatasetWizardManager;
import eu.eudat.logic.managers.UserManager;
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.forms.VisibilityRuleService;
import eu.eudat.models.data.datasetwizard.DataManagentPlanListingModel;
import eu.eudat.models.data.datasetwizard.DatasetWizardModel;
import eu.eudat.models.data.dmp.AssociatedProfile;
import eu.eudat.models.data.helpers.responses.ResponseItem;
import eu.eudat.models.data.security.Principal;
import eu.eudat.models.data.user.composite.PagedDatasetProfile;
import eu.eudat.types.ApiMessageCode;
import org.apache.poi.util.IOUtils;
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.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.transaction.Transactional;
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.UUID;

import static eu.eudat.types.Authorities.ANONYMOUS;


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

    private Environment environment;
    private DatasetManager datasetManager;
    private UserManager userManager;
    private ConfigLoader configLoader;

    @Autowired
    public DatasetWizardController(ApiContext apiContext, Environment environment, DatasetManager datasetManager, UserManager userManager, ConfigLoader configLoader) {
        super(apiContext);
        this.environment = environment;
        this.datasetManager = datasetManager;
        this.userManager = userManager;
        this.configLoader = configLoader;
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/userDmps"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<List<DataManagentPlanListingModel>>> getUserDmps(@RequestBody DatasetWizardAutocompleteRequest datasetWizardAutocompleteRequest, Principal principal) throws IllegalAccessException, InstantiationException {
        List<DataManagentPlanListingModel> dataManagementPlans = DatasetWizardManager.getUserDmps(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetWizardAutocompleteRequest, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<DataManagentPlanListingModel>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/getAvailableProfiles"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<List<AssociatedProfile>>> getAvailableProfiles(@RequestBody DatasetProfileWizardAutocompleteRequest datasetProfileWizardAutocompleteRequest, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, InstantiationException {
        List<AssociatedProfile> dataManagementPlans = DatasetWizardManager.getAvailableProfiles(this.getApiContext().getOperationsContext().getDatabaseRepository().getDmpDao(), datasetProfileWizardAutocompleteRequest);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<List<AssociatedProfile>>().status(ApiMessageCode.NO_MESSAGE).payload(dataManagementPlans));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = {"{id}"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity getSingle(@PathVariable String id, @RequestHeader("Content-Type") String contentType, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
        if(contentType.equals("application/xml")) {
            VisibilityRuleService visibilityRuleService = this.getApiContext().getUtilitiesService().getVisibilityRuleService();
            return this.datasetManager.getDocument(id, visibilityRuleService, contentType);
        }
        else if (contentType.equals("application/msword")) {
            File file = datasetManager.getWordDocument(this.configLoader, id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
            InputStream resource = new FileInputStream(file);
            HttpHeaders responseHeaders = new HttpHeaders();
            responseHeaders.setContentLength(file.length());
            responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            responseHeaders.set("Content-Disposition", "attachment;filename=" + file.getName());
            responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
            responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");

            byte[] content = IOUtils.toByteArray(resource);
            resource.close();
            Files.deleteIfExists(file.toPath());
            return new ResponseEntity<>(content,
                    responseHeaders,
                    HttpStatus.OK);
        }
        else {
            DatasetWizardModel dataset = this.datasetManager.getSingle(id);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/public/{id}"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity getSinglePublic(@PathVariable String id) throws Exception {
        try {
            DatasetWizardModel dataset = this.datasetManager.getSinglePublic(id);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
        }
        catch (Exception ex) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).message(ex.getMessage()));
        }
    }

    @Transactional
    @RequestMapping(method = RequestMethod.DELETE, value = {"{id}"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<Dataset>> delete(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
        new DatasetWizardManager().delete(this.getApiContext(), id);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Deleted"));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.POST, consumes = "application/json", produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<Dataset>> createOrUpdate(@RequestBody DatasetWizardModel profile, Principal principal) throws Exception {
        this.datasetManager.createOrUpdate(profile, principal);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<eu.eudat.data.entities.Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Created").payload(null));
    }

    @RequestMapping(method = RequestMethod.GET, value = {"/getPDF/{id}"})
    public @ResponseBody
    ResponseEntity<byte[]> getPDFDocument(@PathVariable String id) throws IllegalAccessException, IOException, InstantiationException, InterruptedException {
        File file = datasetManager.getWordDocument(this.configLoader, id, this.getApiContext().getUtilitiesService().getVisibilityRuleService());
        String fileName = file.getName();
        if (fileName.endsWith(".docx")){
            fileName = fileName.substring(0, fileName.length() - 5);
        }
        File pdffile = datasetManager.convertToPDF(file, environment, fileName);
        InputStream resource = new FileInputStream(pdffile);

        HttpHeaders responseHeaders = new HttpHeaders();
        responseHeaders.setContentLength(pdffile.length());
        responseHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        responseHeaders.set("Content-Disposition", "attachment;filename=" + pdffile.getName());
        responseHeaders.set("Access-Control-Expose-Headers", "Content-Disposition");
        responseHeaders.get("Access-Control-Expose-Headers").add("Content-Type");

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

    @RequestMapping(method = RequestMethod.GET, value = {"/get/{id}"}, produces = "application/json")
    public ResponseEntity<ResponseItem<PagedDatasetProfile>> getSingle(@PathVariable String id) {
        eu.eudat.data.entities.DatasetProfile profile = this.getApiContext().getOperationsContext().getDatabaseRepository().getDatasetProfileDao().find(UUID.fromString(id));
        eu.eudat.models.data.user.composite.DatasetProfile datasetprofile = userManager.generateDatasetProfileModel(profile);
        PagedDatasetProfile pagedDatasetProfile = new PagedDatasetProfile();
        pagedDatasetProfile.buildPagedDatasetProfile(datasetprofile);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<PagedDatasetProfile>().status(ApiMessageCode.NO_MESSAGE).payload(pagedDatasetProfile));
    }

    @Transactional
    @RequestMapping(method = RequestMethod.GET, value = {"/{id}/unlock"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity<ResponseItem<Dataset>> unlock(@PathVariable(value = "id") UUID id, Principal principal) throws Exception {
        try {
            new DatasetWizardManager().unlock(this.getApiContext(), id);
            return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<Dataset>().status(ApiMessageCode.SUCCESS_MESSAGE).message("Unlocked"));
        } catch (DatasetWizardCannotUnlockException datasetWizardCannotUnlockException) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem<Dataset>().status(ApiMessageCode.ERROR_MESSAGE).message(datasetWizardCannotUnlockException.getMessage()));
        }
    }

    @RequestMapping(method = RequestMethod.POST, value = {"/upload"})
    public ResponseEntity<ResponseItem> datasetXmlImport(@RequestParam("file") MultipartFile file, @RequestParam("dmpId") String dmpId, @RequestParam("datasetProfileId") String datasetProfileId, Principal principal) {
        try {
            Dataset dataset = this.datasetManager.createDatasetFromXml(file, dmpId, datasetProfileId, principal);
            if (dataset != null){
                return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem().status(ApiMessageCode.SUCCESS_MESSAGE));
            }
            else {
                return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful."));
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseItem().status(ApiMessageCode.NO_MESSAGE).message("Import was unsuccessful."));
        }
    }

    @RequestMapping(method = RequestMethod.GET, value = {"profile/{id}"}, produces = "application/json")
    public @ResponseBody
    ResponseEntity getSingleProfileUpdate(@PathVariable String id, @ClaimedAuthorities(claims = {ANONYMOUS}) Principal principal) throws IllegalAccessException, IOException, InstantiationException {
        DatasetWizardModel dataset = this.datasetManager.datasetUpdateProfile(id);
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseItem<DatasetWizardModel>().status(ApiMessageCode.NO_MESSAGE).payload(dataset));
    }
}
