package com.yeejoin.amos.avic.service.impl;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.activation.DataHandler;
import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import com.yeejoin.amos.avic.face.model.AvicCustomPathModel;
import com.yeejoin.amos.avic.face.service.AvicCustomPathService;
import com.yeejoin.amos.avic.face.webservice.FileFransferService;

@WebService(serviceName = "FileFransferService",
		targetNamespace = "http://service.avic.amos.yeejoin.com",
	endpointInterface = "com.yeejoin.amos.avic.face.webservice.FileFransferService")
@Component
public class FileFransferServiceImpl implements FileFransferService {

	@Autowired
	AvicCustomPathService avicCustomPathService;
	
	@Override
	public void useCodetransferFile(DataHandler handler, String fileName, String path, String code) {
		saveFile(handler, fileName, path);
		sendEmail(code, fileName);
	}

	private void saveFile(DataHandler handler, String fileName, String path) {
		InputStream is = null;
		FileOutputStream os = null;
		try {
			is = handler.getInputStream();
			File file = new File(String.format("%s%s%s", path, File.separator, fileName));
			File dir = new File(String.format("%s%s", path, File.separator));
			if (!dir.exists()) {
				dir.mkdirs();
			}
			if (!file.exists()) {
				file.createNewFile();
			}
			os = new FileOutputStream(file);
			int ch;
	        while ((ch = is.read()) != -1) {
	        	os.write(ch);
	        }
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			try {
				if (is != null) {
					is.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	private void sendEmail(String userCode, String fileName) {

	}

	@Override
	public void transferFile(DataHandler handler, String fileName, String path) {
		saveFile(handler, fileName, path);
	}

	@Override
	public void transferPathConfig(AvicCustomPathModel model) {
		if (ObjectUtils.isEmpty(model.getSequenceNbr())) {
			avicCustomPathService.createWithModel(model);
		} else {
			avicCustomPathService.updateWithModel(model);
		}
	}

	


}
