package com.eactive.eai.rms.onl.common.service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.eactive.eai.agent.command.Command;
import com.eactive.eai.agent.command.CommonCommand;
import com.eactive.eai.rms.common.base.OnlBaseService;
import com.eactive.eai.rms.common.datasource.DataSourceType;
import com.eactive.eai.rms.onl.common.util.FileWriteUtil;
import com.eactive.eai.rms.onl.loader.service.TransactionLoaderService;

@Service("eaiCmReflectionService")
public class EaiCmReflectionService extends OnlBaseService {

    /**
    * Logger for this class
    */
    private static final Logger logger = Logger.getLogger(EaiCmReflectionService.class);

    @Autowired
    @Qualifier("loaderService") 
    private TransactionLoaderService loaderService; 

    public HashMap<String,ArrayList<String>> insertFileData(DataSourceType dt, File[] typeDirs) throws Exception{
    	HashMap<String,ArrayList<String>> result = new HashMap<String,ArrayList<String>>();
    	ArrayList<String> al = new ArrayList<String>();
    	ArrayList<String> al2 = new ArrayList<String>();
		for(File typeDir : typeDirs){
			if (typeDir.isDirectory()){
				if (FileWriteUtil.INTERFACE.equals(typeDir.getName())){
					String path = typeDir.getAbsolutePath() + File.separator;
					File subDir = new File(path);
					String[] sublistFiles = subDir.list();
					al = new ArrayList<String>();
					al2 = new ArrayList<String>();
					if (sublistFiles != null && sublistFiles.length > 0) {
						for(String fileName : sublistFiles){ 
							String data = fileName.substring(0,fileName.length()-4);
							al.add(data);
							logger.info("EaiCMReflectionService interface : fileName =" + fileName +" , data =" + data +" , path = "+ path);
							loaderService.insertInterfaceLoading(dt,path , fileName);
							HashMap map = (HashMap)loaderService.parse(path + fileName);
							ArrayList<HashMap> list = (ArrayList<HashMap>)map.get("TSEAIHS04");
							if (list != null && list.size()>0){
								for(HashMap row : list){
									//내부표준message
									String bzwkKey = (String)row.get("BZWKSVCKEYNAME");
									al2.add(bzwkKey);
								}
							}
						}
					}
					if (al.size()>0) {
						result.put(typeDir.getName(), al);
					}
					if (al2.size()>0) {
						result.put(typeDir.getName()+"EXT", al2);
					}
					
				}else if (FileWriteUtil.B2B.equals(typeDir.getName())){
					String path = typeDir.getAbsolutePath() + File.separator;
					File subDir = new File(path);
					String[] sublistFiles = subDir.list();
					al = new ArrayList<String>();
					if (sublistFiles != null && sublistFiles.length > 0) {
						for(String fileName : sublistFiles){
							String data = fileName.substring(0,fileName.length()-4);
							al.add(data);
							loaderService.insertB2BLoading(dt, path, fileName);
						}
					}
					if (al.size()>0) {
						result.put(typeDir.getName(), al);
					}

				} else if (FileWriteUtil.C2R.equals(typeDir.getName())){
					
					String path = typeDir.getAbsolutePath() + File.separator;
					File subDir = new File(path);
					String[] sublistFiles = subDir.list();
					al = new ArrayList<String>();
					if (sublistFiles != null && sublistFiles.length > 0) {
						for(String fileName : sublistFiles){
							String data = fileName.substring(0,fileName.length()-4);
							al.add(data);
							loaderService.insertC2RLoading(dt, path, fileName);
						}
					}
					if (al.size()>0) {
						result.put(typeDir.getName(), al);
					}
					
				} else if (FileWriteUtil.B2B_EXT.equals(typeDir.getName())){
				
					String path = typeDir.getAbsolutePath() + File.separator;
					File subDir = new File(path);
					String[] sublistFiles = subDir.list();
					al = new ArrayList<String>();
					if (sublistFiles != null && sublistFiles.length > 0) {
						for(String fileName : sublistFiles){
							String data = fileName.substring(0,fileName.length()-4);
							al.add(data);
							loaderService.insertB2BExtLoading(dt, path, fileName);
						}
					}
					if (al.size()>0) {
						result.put(typeDir.getName(), al);
					}
					
				} else if (FileWriteUtil.ADAPTER.equals(typeDir.getName())){
					String path = typeDir.getAbsolutePath() + File.separator;
					File subDir = new File(path);
					String[] sublistFiles = subDir.list();
					al = new ArrayList<String>();
					if (sublistFiles != null && sublistFiles.length > 0) {
						for(String fileName : sublistFiles){
							String data = fileName.substring(0,fileName.length()-4);
							al.add(data);
							loaderService.insertAdapterLoading(dt,path , fileName);
						}
					}
					if (al.size()>0) {
						result.put(typeDir.getName(), al);
					}
				}else if (FileWriteUtil.MESSAGEKEY.equals(typeDir.getName())){
					String path = typeDir.getAbsolutePath() + File.separator;
					File subDir = new File(path);
					String[] sublistFiles = subDir.list();
					al = new ArrayList<String>();
					if (sublistFiles != null && sublistFiles.length > 0) {
						for(String fileName : sublistFiles){
							String data = fileName.substring(0,fileName.length()-4);
							al.add(data);
							loaderService.insertMessageKeyLoading(dt, path, fileName);
						}
					}
					if (al.size()>0) {
						result.put(typeDir.getName(), al);
					}
				}
			}
		}
		return result;
    }
	public boolean interfaceMemorySync(ArrayList<String> list, ArrayList<String> list2) throws Exception {
		Vector eaiSvcNames = new Vector();
		Vector bzwkKeys = new Vector();
		if (list != null && list.size() > 0 ){
			for (String key : list) {
				eaiSvcNames.add(key);
			}
		}
		if (list2 != null && list.size() > 0 ){
			for (String key : list2) {
				bzwkKeys.add(key);
			}
		}
		long currentTime = System.currentTimeMillis();
		if (eaiSvcNames.size() > 0){
			syncResult(new CommonCommand("com.eactive.eai.agent.eaimessage.ReloadEAIMessageListCommand"),eaiSvcNames);
			syncResult(new CommonCommand("com.eactive.eai.agent.bizkey.ReloadBizKeyListCommand"),eaiSvcNames);
			syncResult(new CommonCommand("com.eactive.eai.agent.b2bextractor.ReloadB2BExtractListCommand"),eaiSvcNames);
		}
		if (bzwkKeys.size() > 0 ){
			syncResult(new CommonCommand("com.eactive.eai.agent.kbmessage.ReloadKBMessageListCommand"),bzwkKeys);
		}
   
		logger.info(">> 메모리동기화   처리시간(ms) : "+ (System.currentTimeMillis() - currentTime));
		return true;
	}
	public boolean b2bMemorySync(ArrayList<String> list) throws Exception {
		Vector tseaiHE03V = new Vector();
		
		for (String key : list) {
			tseaiHE03V.add(key);
		}
		
		long currentTime = System.currentTimeMillis();
		if (tseaiHE03V.size() > 0){ 
			syncResult(new CommonCommand("com.eactive.eai.agent.b2bservice.ReloadB2BServiceListCommand"),tseaiHE03V);
		}
		logger.info(">> 메모리동기화   처리시간(ms) : "+ (System.currentTimeMillis() - currentTime));
		
		return true;
	}	
	public boolean c2rMemorySync(ArrayList<String> list) throws Exception {
		Vector tseaiHE04V = new Vector();
		
		for (String key : list) {
			tseaiHE04V.add(key);
		}
		
		long currentTime = System.currentTimeMillis();
		if (tseaiHE04V.size() > 0){ 
			syncResult(new CommonCommand("com.eactive.eai.agent.b2bservice.ReloadC2RServiceListCommand"),tseaiHE04V);
		}
		logger.info(">> 메모리동기화   처리시간(ms) : "+ (System.currentTimeMillis() - currentTime));
		
		return true;
	}
	public boolean adapterMemorySync(ArrayList<String> list) throws Exception {
		Vector tseaiFR04V = new Vector();
		
		for (String key : list) {
			tseaiFR04V.add(key);
		}
		
		long currentTime = System.currentTimeMillis();
		if (tseaiFR04V.size() > 0){ 
			syncResult(new CommonCommand("com.eactive.eai.agent.messagekey.ReloadMessageKeyListCommand"),tseaiFR04V);
		}
		logger.info(">> 메모리동기화   처리시간(ms) : "+ (System.currentTimeMillis() - currentTime));
		
		return true;
	}
    private void syncResult(Command command ,Vector names ) throws Exception {
        //layout 동기화 service 에는 transaction 때문에 문제의 소지가 있음
        HashMap receive =new HashMap(); 
		if (names != null && names.size() > 0){
			command.setArgs(names);
			receive = agentUtilService.broadcast(command);
		}

        String status = "success";
        for (Object o : receive.keySet()){
        	String key = (String)o;
        	if (receive.get(key) == null || !"success".equals(receive.get(key)) ){
    			status = "error";
    			break;
        	}
        }
        if (logger.isInfoEnabled()){
        	logger.info(this.getClass().toString()+"] command = "+command.getName().toString()+ " names="+names + " status = " + status + " message = " + receive.toString());
        }
        
        if (!"success".equals(status)){
        	throw new Exception("메모리 동기화 오류 : " + "command = "+command.getName().toString()+ " names="+names + " status = " + status + " message = " + receive.toString());
        }
    	
    }
    
}
