package com.ffii.tbms.api.web;

import java.io.IOException;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import com.ffii.core.utils.Params;
import com.ffii.core.web.AbstractController;
import com.ffii.tbms.api.service.AuthenticationService;
import com.ffii.tbms.file.File;
import com.ffii.tbms.file.FileBlob;
import com.ffii.tbms.file.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping(value = "api/")

public class MainApiController extends AbstractController {

    @Autowired
    AuthenticationService authenticationService;

    @Autowired
    private FileService fileService;


    @RequestMapping(value = "/dl/{id}/{skey}/{filename}", method = { RequestMethod.GET, RequestMethod.POST })
    public void download(HttpServletResponse response, @RequestParam String deviceId, @RequestParam String token, Model model,
            @RequestParam(defaultValue = "false") boolean dl,
            @PathVariable int id, @PathVariable String skey) throws IOException {

        Map<String, Object> userData = authenticationService.findUserByAccessToken(deviceId, token);
        if (userData == null) {
            model.addAllAttributes(authenticationService.getNoUserFoundMap());
            return;
        }

        File file = fileService.findFileByIdAndKey(id, skey);

        if (file != null) {
            FileBlob fileBlob = fileService.findFileBlobByFileId(id);

            response.reset();
            response.setContentType(file.getMimetype());
            response.setContentLength((int) file.getFilesize());
            response.setHeader("Content-Transfer-Encoding", "binary");
            response.setHeader("Content-Disposition", String.format("%s; filename=\"%s\"", dl ? "attachment" : "inline",
                    response.encodeURL(file.getFilename())));

            ServletOutputStream out = response.getOutputStream();

            try {
                out.write(fileBlob.getBytes());
                out.flush();
                out.close();
            } catch (IOException e) {
                logger.warn(e.getMessage());
            } finally {
                out.close();
                model.addAttribute(Params.SUCCESS, Boolean.TRUE);
            }
        } else {
            logger.info("*** 400 BAD REQUEST ***");
            response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            model.addAttribute(Params.SUCCESS, Boolean.FALSE);
        }
    }

}