package com.jasamedika.medifirst2000.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.nio.charset.Charset;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
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 com.jasamedika.medifirst2000.constants.MessageResource;
import com.jasamedika.medifirst2000.controller.base.LocaleController;
import com.jasamedika.medifirst2000.core.web.WebConstants;
import com.jasamedika.medifirst2000.entities.DokumenTemplate;
import com.jasamedika.medifirst2000.service.ProdukHukumService;
import com.jasamedika.medifirst2000.util.rest.RestUtil;
import com.jasamedika.medifirst2000.vo.AgamaVO;
import com.jasamedika.medifirst2000.vo.DokumenTemplateVO;

@RestController
@RequestMapping("/produk-hukum")
public class ProdukHukumController extends LocaleController<AgamaVO>   {
	
	@Autowired
	private ProdukHukumService produkHukumService;
	
	private static final Logger LOGGER = LoggerFactory
			.getLogger(ProdukHukumController.class);

	@RequestMapping(value="/save", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
	public ResponseEntity<String> uploadTemplateSurat(
			@RequestBody DokumenTemplateVO dokumenTemplateVO,
			HttpServletRequest request) {
		String result = produkHukumService.uploadDocumentTemplateSurat(dokumenTemplateVO);
		if (result != null) {
			if (!result.isEmpty()) {
				mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_SUCCESS, getMessage(MessageResource.LABEL_SUCCESS, request));
				return RestUtil.getJsonResponse(result, HttpStatus.CREATED, mapHeaderMessage);
			} else {
				mapHeaderMessage.put(WebConstants.HttpHeaderInfo.LABEL_ERROR, "Processing data error returns empty data");
				return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
			}
		} else {
			return RestUtil.getJsonHttptatus(HttpStatus.INTERNAL_SERVER_ERROR, mapHeaderMessage);
		}		
	}

	@RequestMapping(value="/download/{id}", method = RequestMethod.GET)
    public void downloadFileDokumenTemplate(HttpServletResponse response, @PathVariable("id") Integer id) throws IOException {
		DokumenTemplate result= produkHukumService.findById(id);
	    File file = new File(result.getFileLocation());
       System.out.println();
	    if(!file.exists()){
            String errorMessage = "Sorry. The file you are looking for does not exist";
            System.out.println(errorMessage);
            OutputStream outputStream = response.getOutputStream();
            outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
            outputStream.close();
            return;
        }
         
        String mimeType= URLConnection.guessContentTypeFromName(file.getName());
        if(mimeType==null){
            System.out.println("mimetype is not detectable, will take default");
            mimeType = "application/octet-stream";
        }
         
        System.out.println("mimetype : "+mimeType);
         
        response.setContentType(mimeType);
         
        /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser 
            while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
        response.setHeader("Content-Disposition", String.format("inline; filename=\"" + result.getFileName() +"\""));
 
         
        /* "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));
 
        //Copy bytes from source to destination(outputstream in this example), closes both streams.
        FileCopyUtils.copy(inputStream, response.getOutputStream());
    }
	@RequestMapping(value = "/get-all", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
	public List<DokumenTemplate> getAllDokumenTemplate(
			@RequestParam(value = "page", required = false, defaultValue = "0") Integer page,
			@RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit,
			@RequestParam(value = "sort", required = false, defaultValue = "namaSurat") String sort,
			@RequestParam(value = "dir", required = false, defaultValue = "asc") String dir,
			@RequestParam(value = "dateStart", required = false) String dateStart,
			@RequestParam(value = "dateEnd", required = false) String dateEnd,
			@RequestParam(value = "id", required = false) Integer suratId) {
		List<DokumenTemplate> resultPageMap = produkHukumService.getAllDokumenTemplate(page, limit, sort, dir, dateStart, dateEnd, suratId);

		return resultPageMap;
	}
}
