package eu.dnetlib.usagestats.controllers;

import eu.dnetlib.usagestats.services.SushiLiteService;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;

/**
 * Created by tsampikos on 10/4/2017.
 */
@RestController
class SushiLiteController {

    private final Logger log = Logger.getLogger(this.getClass());

    private final SushiLiteService sushiLiteService;
    
    @Value("${download.folder}")
    private String download_folder;


    public SushiLiteController(SushiLiteService sushiLiteService) {
        this.sushiLiteService = sushiLiteService;
    }

    @RequestMapping(value = "/sushilite/GetReport/", method = RequestMethod.GET)
    public ResponseEntity<String> getReport(@RequestParam(value = "Report", defaultValue = "") String reportP, @RequestParam(value = "Release", defaultValue = "4") String release, @RequestParam(value = "RequestorID", defaultValue = "anonymous") String requestorId,
            @RequestParam(value = "BeginDate", defaultValue = "") String beginDate, @RequestParam(value = "EndDate", defaultValue = "") String endDate, @RequestParam(value = "RepositoryIdentifier", defaultValue = "") String repositoryIdentifier,
            @RequestParam(value = "ItemIdentifier", defaultValue = "") String itemIdentifier, @RequestParam(value = "ItemDataType", defaultValue = "") String itemDataType,
            @RequestParam(value = "hasDOI", defaultValue = "") String hasDoi, @RequestParam(value = "Granularity", defaultValue = "Monthly") String granularity, @RequestParam(value = "Callback", defaultValue = "") String callback,
            @RequestParam(value = "Pretty", defaultValue = "") String pretty,
            //added for compression case report
            @RequestHeader(value = "User-Agent", required = false) String userAgent) throws InterruptedException, Exception {
        log.info("Sushi Report request: " + reportP + " from " + requestorId);
        log.info("repository identifier: " + repositoryIdentifier + " - item identifier: " + itemIdentifier);

        String report = sushiLiteService.displayReport(reportP, release, requestorId, beginDate, endDate, repositoryIdentifier, itemIdentifier, itemDataType, hasDoi, granularity, callback, pretty, userAgent);
        if (report.indexOf(".zip") < 0) {
            return new ResponseEntity<>(report, HttpStatus.OK);
        } else {
            URI reportZipURL = new URI(report);
            HttpHeaders httpHeaders = new HttpHeaders();
            httpHeaders.setLocation(reportZipURL);
            return new ResponseEntity<>(httpHeaders, HttpStatus.SEE_OTHER);
        }

    }

    @RequestMapping(value = "/download/{file_name}", method = RequestMethod.GET)
    public void downloadFile(HttpServletResponse response, @PathVariable("file_name") String filetoDownload) throws IOException {
        File file = new File(download_folder+"/" + filetoDownload + ".zip");

        String mimeType = "application/octet-stream";

        response.setContentType(mimeType);

        /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
        response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
        response.setContentLength((int) file.length());
        InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }

}
