package info.bukova.isspst.storage;

import info.bukova.isspst.data.FileMetainfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by pepa on 2.2.15.
 */

@Controller
public class StorageController {

	@Autowired
	private DocumentFileStorage documentStorage;
	private static final Logger logger = LoggerFactory.getLogger(StorageController.class);

	@RequestMapping(value = "dl/{path}/{name}")
	public void viewFile(HttpServletResponse response, @PathVariable("path") String path,
						 @PathVariable("name") String name) {
		ServletOutputStream os = null;

		try {
			os = response.getOutputStream();
			FileMetainfo metainfo = new FileMetainfo();
			metainfo.setPathInFilesystem(path);
			byte[] data = null;

			try {
				data = documentStorage.fileData(metainfo);
				metainfo.setContentType(MimeTypes.getContentType(data, path));
			} catch (StorageException e) {
				response.sendError(404);
			}

			if (data != null) {
				response.setContentType(metainfo.getContentType());
				response.setContentLength(data.length);

				os.write(data, 0, data.length);
				os.flush();
				os.close();
			}
		} catch (IOException e) {
			logger.error("I/O error: " + e.getMessage());
		} finally {
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

}
