package com.eactive.eai.batch.common;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Properties;

import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.property.PropManager;
import com.eactive.eai.common.util.Logger;
import com.sennet.gator.EzGatorFile;
import com.sennet.gator.JobType;
import com.sennet.gator.console.main.EzGatorExecutor;

public class EzgatorUtil {

	private static String CBS_DIR_INFO     = "CBSDirInfo";
	
	private static Logger logger = Logger.getLogger(Logger.LOGGER_ADAPTER);

	public static EzGatorFile[] listFiles(String server, int port, String path, HashMap<Integer, String> extmap) throws IOException {

		EzGatorExecutor executor = new EzGatorExecutor();
		try {

			Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
			String keyPath = prop.getProperty("mft.key.path");
			String username = prop.getProperty("mft.user.name");
			executor.setIp(server); // API가 접속하는 서버, 송신할 파일이 있는 서버
			executor.setPort(port);
			executor.setUserId(username);
			executor.setPassword("");
			executor.setRemoteServerIp(server);
			executor.setRemoteServerPort(port);
			executor.setJobType(JobType.GETDIRINFO); // 작업 종류
			executor.setSrcFile("");
			if (extmap != null) {
				executor.setOption("24h");
			}
			executor.setPrivateKeyPath(keyPath);

			executor.init();
			executor.connect();
			executor.login();

			EzGatorFile[] ezGatorFiles = null;
			if (extmap == null) {
				ezGatorFiles = executor.listFiles(path);
			} else {
				ArrayList<EzGatorFile> list = new ArrayList<EzGatorFile>();
				for (int inx = 0; inx < extmap.size(); inx++) {
					String ext = extmap.get(inx);
					EzGatorFile[] ezGatorFilesTemp = executor.listFiles(path + "/*." + ext);
					logger.debug("DHJEONG==>server:" + server + ",port:" + port + ",username:" + username + ",path:" + path + ";" + ext);
					for (int jnx = 0; jnx < ezGatorFilesTemp.length; jnx++) {
						list.add(ezGatorFilesTemp[jnx]);
					}
				}
				ezGatorFiles = new EzGatorFile[list.size()];
				list.toArray(ezGatorFiles);
			}
			logger.info("[MFT를 통해 검색된 체크파일 개수]server:" + server + ",port:" + port + ",path:" + path + ",files-->" + ezGatorFiles.length);
			for (int inx = 0; inx < ezGatorFiles.length; inx++) {
				logger.debug("[MFT를 통해 검색된 체크파일 목록]" + ezGatorFiles[inx].getRawListing());
			}
			return ezGatorFiles;

		} catch (Throwable t) {
			String arg[] = new String[2];
			arg[0] = server;
			arg[1] = "" + port;
			String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg);
			logger.error(errMsg, t);
			throw new IOException(t);
		} finally {
			executor.disconnect();
		}
	}

	public static boolean retrieve(String server, int port, String remote, String localPath) throws Exception {

		logger.info("[retrieve]remote  ------->" + remote + ", localPath---->" + localPath);

		File chkDir = new File(localPath);

		chkDir.mkdirs(); // 상위 디렉토리 미 존재시에도 write 한다.
		try {
			chkDir.setReadable(true, false);
			chkDir.setWritable(true, false);
			chkDir.setExecutable(true, false);
			File p1 = chkDir.getParentFile();
			p1.setReadable(true, false);
			p1.setExecutable(true, false);
			p1.setWritable(true, false);
			File p2 = p1.getParentFile();
			p2.setReadable(true, false);
			p2.setExecutable(true, false);
			p2.setWritable(true, false);
			File p3 = p2.getParentFile();
			p3.setReadable(true, false);
			p3.setExecutable(true, false);
			p3.setWritable(true, false);
			File p4 = p3.getParentFile();
			p4.setReadable(true, false);
			p4.setExecutable(true, false);
		} catch (Exception e) {
			//
		}

		String delimiter = StringUtil.getDirDelimiter(localPath);
		String fName = remote.substring(remote.lastIndexOf(delimiter) + 1);

		EzGatorExecutor executor = new EzGatorExecutor();
		try {
			Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
			String localServer = prop.getProperty("mft.local.server");
			String keyPath     = prop.getProperty("mft.key.path");
			String username    = prop.getProperty("mft.user.name");

			int localPort = Integer.parseInt(prop.getProperty("mft.local.port"));
			executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버
			executor.setPort(localPort);
			executor.setUserId(username);
			executor.setPassword("");
			executor.setJobType(JobType.RECVFILE); // 작업 종류
			executor.setPrivateKeyPath(keyPath);
			executor.setRemoteServerIp(server); // 수신 서버
			executor.setRemoteServerPort(port);
			executor.setSrcFile(remote);
			executor.setSrcSuffix(null);
			executor.setOption("ir");
			executor.setDestFile(localPath + fName); // 수신할 파일의 절대경로
			executor.setDestSuffix(null);
			executor.init();
			executor.connect();
			executor.login();
			if (!executor.recvServerFile()) {
				logger.warn("Command failed: " + executor.getErrorMsg());
				throw new Exception(executor.getErrorMsg());
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		} finally {
			executor.disconnect();
		}

		return true;
	}

	public static boolean store(String server, int port, String remote, String localPath) throws Exception {

		EzGatorExecutor executor = new EzGatorExecutor();

		try {
			localPath = localPath.replace("\\r$", "");
			Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
			String localServer = prop.getProperty("mft.local.server");
			int localPort = Integer.parseInt(prop.getProperty("mft.local.port"));
			String keyPath = prop.getProperty("mft.key.path");
			String username    = prop.getProperty("mft.user.name");
			executor.setPrivateKeyPath(keyPath);
			executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버
			executor.setPort(localPort);
			executor.setUserId(username);
			executor.setPassword("");
			executor.setJobType(JobType.SENDFILE); // 작업 종류
			executor.setRemoteServerIp(server); // 수신 서버
			executor.setRemoteServerPort(port);
			executor.setSrcFile(localPath);
			executor.setSrcSuffix(null);
			executor.setOption("ir");
			executor.setDestFile(remote); // 수신할 파일의 절대경로
			executor.setDestSuffix(null);
			executor.init();
			executor.connect();
			executor.login();
			boolean success = false;
			try {
				success = executor.sendServerFile();
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				throw new Exception(e.getMessage());
			}
			if (!success) {
				logger.warn("Command failed: " + executor.getErrorMsg());
				throw new Exception(executor.getErrorMsg());
			}
		} catch (Throwable e) {
			logger.error(e.getMessage(), e);
			throw new Exception(e.getMessage());
		} finally {
			executor.disconnect();
		}
		return true;
	}

	public static boolean delete(String server, int port, String fullfilename) throws IOException {

		EzGatorExecutor executor = new EzGatorExecutor();
		try {
			fullfilename = fullfilename.replace("\\r$", "");
			Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
			String localServer = prop.getProperty("mft.local.server");
			int localPort      = Integer.parseInt(prop.getProperty("mft.local.port"));
			String keyPath     = prop.getProperty("mft.key.path");
			String username    = prop.getProperty("mft.user.name");
			executor.setPrivateKeyPath(keyPath);
			executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버
			executor.setPort(localPort);
			executor.setUserId(username);
			executor.setPassword("");
			executor.setRemoteServerIp(server); // 수신 서버
			executor.setRemoteServerPort(port);
			executor.setJobType(JobType.DELETEFILE); // 작업 종류
			executor.setSrcFile(fullfilename);
			executor.init();
			executor.connect();
			executor.login();
			return executor.deleteServerFile();
		} catch (Exception e) {
			String arg[] = new String[2];
			arg[0] = server;
			arg[1] = "" + port;
			String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg);
			logger.error(errMsg, e);
			throw new IOException(e);
		} finally {
			executor.disconnect();
		}
	}

	public static boolean rename(String server, int port, String srcname, String tarname) throws IOException {

		EzGatorExecutor executor = new EzGatorExecutor();
		
		try {
			srcname = srcname.replace("\\r$", "");
			tarname = tarname.replace("\\r$", "");
			Properties prop = PropManager.getInstance().getProperties( CBS_DIR_INFO );
			String localServer = prop.getProperty("mft.local.server");
			int localPort = Integer.parseInt(prop.getProperty("mft.local.port"));
			String keyPath = prop.getProperty("mft.key.path");
			String username    = prop.getProperty("mft.user.name");

			executor.setPrivateKeyPath(keyPath);
			executor.setIp(localServer); // API가 접속하는 서버, 송신할 파일이 있는 서버
			executor.setPort(localPort);
			executor.setUserId(username);
			executor.setPassword("");
			executor.setRemoteServerIp(server); // 수신 서버
			executor.setRemoteServerPort(port);
			executor.setJobType(JobType.RENAMEFILE); // 작업 종류
			executor.setSrcFile(srcname);
			executor.setDestFile(tarname);
			executor.setOption("ov");
			executor.init();
			executor.connect();
			executor.login();
			return executor.renameServerFile();
		} catch (Exception e) {
			String arg[] = new String[2];
			arg[0] = server;
			arg[1] = "" + port;
			String errMsg = ExceptionUtil.getErrorCode("BECEAIMEU017", arg);
			logger.error(errMsg, e);
			throw new IOException(e);
		} finally {
			executor.disconnect();
		}
	}
}
