package edu.prlab.tyler.iotgateway.cloud.controllers;

import edu.prlab.tyler.iotgateway.cloud.pojo.Document;
import edu.prlab.tyler.iotgateway.cloud.services.DocumentService;
import edu.prlab.tyler.iotgateway.cloud.services.PrivacyPolicyReportService;
import edu.prlab.tyler.iotgateway.cloud.util.CodeTools;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/document")
public class DocumentController {

    private DocumentService documentService;
    private PrivacyPolicyReportService privacyPolicyReportService;

    public DocumentController(DocumentService documentService, PrivacyPolicyReportService privacyPolicyReportService) {
        this.documentService = documentService;
        this.privacyPolicyReportService = privacyPolicyReportService;
    }

    @PostMapping
    public ResponseEntity<Document> uploadFile(@RequestPart MultipartFile file) throws IOException {
        return documentService.add(file)
                .map(ResponseEntity::ok)
                .orElseGet(() -> ResponseEntity.noContent().build());
    }

    @GetMapping("/{udn}")
    public ResponseEntity<ByteArrayResource> findFile(@PathVariable String udn) {
        return privacyPolicyReportService.readByDevice(udn)
                .map(privacyReport->privacyReport.getDocument().getId())
                .flatMap(id->documentService.readFile(id))
                .map(document -> ResponseEntity.ok()
                        .contentType(MediaType.parseMediaType(document.getFileType()))
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename* = UTF-8''" + CodeTools.encode(document.getFileName()))
                        .body(new ByteArrayResource(document.getBytes())))
                .orElseGet(() -> ResponseEntity.noContent().build());
    }

}
