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

import java.io.IOException;
import java.util.HashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.View;

import com.eactive.eai.rms.common.base.OnlBaseAnnotationController;
import com.eactive.eai.rms.common.datasource.DataSourceContextHolder;
import com.eactive.eai.rms.common.datasource.DataSourceTypeManager;
import com.eactive.eai.rms.common.interceptor.InterceptorSkipController;
import com.eactive.eai.rms.onl.manage.adapter.adapter.AdapterManService;
import com.google.gson.Gson;

/**
 * <pre>
 *     1. 기능 : NODE 장애시 어댑터를 재기동하는 클래스
 * </pre>
 *
 * @author : music75
 * @version : $Revision: 1.26.2.5 $
 * @since : rts 1.0
 */
@SuppressWarnings("unchecked")
@Controller
public class AdapterInstanceRecoverController extends OnlBaseAnnotationController implements InterceptorSkipController{
    private static final Logger logger = Logger.getLogger(AdapterInstanceRecoverController.class);
    
    @Autowired
    private AdapterManService service;	
	
    /**
     * NODE 장애시 어댑터를 재기동 하는 메소드
     * 
     *  Clinet 이고 이중화가 안되어 있는 것만 해당됨
     * 
     * @param request
     * @param response
     * @param schema
     * @param status
     * @return
     * @throws Exception
     */

	@RequestMapping(value= "/adapterInstanceRecover.do")
	private View recover(HttpServletRequest request, HttpServletResponse response,String serviceType,String node) throws Exception {
		
		CopyOnWriteArrayList<HashMap<String,String>> al = new CopyOnWriteArrayList<HashMap<String,String>>();
		HashMap<String,Object> resultMap = new HashMap<String,Object>();
		
		if (serviceType != null && node != null) {
			if (!DataSourceTypeManager.isOnlineForName(serviceType)){
				HashMap<String,Object> result = new HashMap<String,Object>();
				result.put("status", "error");
				result.put("message", "정의 되지 않은 서비스 타입입니다. 받은 서비스 타입="+ serviceType);
				writeJsonString(response,result);
				return null;
			}
			try{
				DataSourceContextHolder.setDataSourceType(DataSourceTypeManager.getDataSourceTypeBySchema(serviceType));
				if(!service.isTakeOverCheck()){
					HashMap<String,Object> result = new HashMap<String,Object>();
					result.put("status", "error");
					result.put("message", "NODE가 1개만 존재합니다.");
					writeJsonString(response,result);
					return null;
					
				}
				
				al = service.recover(node);
				if (al.size()==0){
					resultMap.put("status", "success");
				}else{
					resultMap.put("status", "error");
					resultMap.put("message","오류 건수 = "+ al.size());
					resultMap.put("errorList", al);
				}
			}catch(Exception e){
				resultMap.put("status", "error");
				resultMap.put("message", e.getMessage());
			}
			writeJsonString(response,resultMap);
		}

		return null;
	}
	private void writeJsonString(HttpServletResponse response , HashMap<String,Object> resultMap){
		Gson gson = new Gson();
		String jsonStr = gson.toJson(resultMap);
		
		ServletOutputStream sos = null;
    	try {
    		sos = response.getOutputStream();
    		sos.write(jsonStr.getBytes());
    	} catch( Exception e ) {
    		logger.error(e);
    	} finally {
    		if( sos != null )try {sos.close();} catch (IOException e) {}
    	}
    	
	}	
}
