package com.jasamedika.medifirst2000.service.impl;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.jasamedika.medifirst2000.dao.AntrianPasienDiPeriksaDao;
import com.jasamedika.medifirst2000.dao.FileDirectoryDao;
import com.jasamedika.medifirst2000.entities.AntrianPasienDiPeriksa;
import com.jasamedika.medifirst2000.entities.FileDirectory;
import com.jasamedika.medifirst2000.service.UploadDownloadImageService;
import com.jasamedika.medifirst2000.util.CommonUtil;
import com.jasamedika.medifirst2000.vo.UploadImageVO;

@Service("UploadImageService")
public class UploadDownloadImageServiceImpl implements UploadDownloadImageService{
	
	@Autowired
	private FileDirectoryDao fileDirectoryDao;
	
	@Autowired
	private AntrianPasienDiPeriksaDao antrianPasienDiPeriksaDao;
	
	public Map<String, Object> uploadImage(UploadImageVO vo){
		Map<String, Object> result = new HashMap<>();
		if (CommonUtil.isNotNullOrEmpty(vo.getImageEncode())) {
			try {
				if(CommonUtil.isNotNullOrEmpty(vo)) {
					if(CommonUtil.isNotNullOrEmpty(vo.getNoRegistrasi())) {
						AntrianPasienDiPeriksa antrianPasienDiPeriksa = antrianPasienDiPeriksaDao.findOne(vo.getNoRegistrasi());
						if(CommonUtil.isNotNullOrEmpty(antrianPasienDiPeriksa)) {
							FileDirectory model = new FileDirectory();
							
							Map<String, Object> checkModel = fileDirectoryDao.getOneByNoRegistrasi(antrianPasienDiPeriksa.getNoRec());
							if(CommonUtil.isNotNullOrEmpty(checkModel)) {
								model.setNoRec((String) checkModel.get("noRec"));
							}
							if(CommonUtil.isNotNullOrEmpty(vo.getImageEncode())) {
								String[] data = vo.getImageEncode().split(",");
								
								if(CommonUtil.isNotNullOrEmpty(data[0])) {
									model.setFileTape(data[0]);
								}
								if(CommonUtil.isNotNullOrEmpty(data[1])) {
									byte[] file = Base64.decodeBase64(data[1]);
									model.setFile(file);
								}
							}
							if(CommonUtil.isNotNullOrEmpty(antrianPasienDiPeriksa)) {
								model.setNoRegistrasi(antrianPasienDiPeriksa);
							}
							if(CommonUtil.isNotNullOrEmpty(model)) {
								FileDirectory fileDirectoryResult = fileDirectoryDao.save(model);
								result.put("norec", fileDirectoryResult.noRec);
							}
						}
					}
				}
			} catch (Exception e) {
				System.out.println(e.toString());
			}
		}
		return result;
	}
	
	@Override
	public Map<String, Object> download(String noRegistrasi){
		Map<String, Object> result = new HashMap<>();
		Map<String, Object> data = fileDirectoryDao.getOneByNoRegistrasi(noRegistrasi);
		if(CommonUtil.isNotNullOrEmpty(data)) {
			result.put("image", data.get("fileTape")+","+Base64.encodeBase64String((byte[])data.get("file")));
		}
		return result;
	}
}
