package com.sagacloud.utils;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//import com.sagacloud.json.JSONArray;
//import com.sagacloud.json.JSONObject;
//import com.sagacloud.json.JSONValue;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sagacloud.broadcast.MessageHandler;
import com.sagacloud.cache.ProPasCache;
import com.sagacloud.dict.TypeToInfosMap;
import com.sagacloud.endpoints.tagset.ObjectTag;
import com.zillion.database.agent.ZillionAgent;

public class StartupThread extends Thread {
	private static final Logger log = LoggerFactory.getLogger(StartupThread.class);
	ZillionAgent agent = null;
	Hashtable<String,String> equipmentType = null;
	public StartupThread() {
	}

	private volatile boolean stop = false;

	public void requestStop() {
		stop = true;
		try {
			this.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void run() {
		agent = ZillionAgentProvider.GetAgent();

		log.info("======init====== createTables");
		createTables();
		log.info("======init====== OssUtils.init()");
		OssUtils.init();
		//ParaTypeCache.synParaTypeByFuncId();
		log.info("======init====== MessageHandler.init()");
		MessageHandler.init();
		log.info("======init====== TypeToInfosMap.synCache()");
		TypeToInfosMap.synCache();
		log.info("======init====== ProPasCache.synCache()");
		ProPasCache.synCache();
		log.info("======init====== ObjectTag.objectTagCacheInit()");
		ObjectTag.objectTagCacheInit();
//		ColdStationManager.Instance().Start();

		while (true) {

			try {
				Thread.sleep(30 * 60 * 1000L);

				//ParaTypeCache.synParaTypeByFuncId();
				ProPasCache.synCache();
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}

	public void createTables() {
		this.createDb();

		List<String> dbTableLst = new ArrayList<>(64);

		String jsonStr = "{\"QueryType\":\"table_list\"}";
		JSONObject json = JSONObject.parseObject(jsonStr);
		json.put("Database", OssUtils.getProperty("database.name"));
		JSONObject resultJSON1 = null;
		JSONObject resultJSON2 = null;
		try {
			resultJSON1 = agent.Query(json);
			json.put("Database", OssUtils.getProperty("fjd.database.name"));
			resultJSON2 = agent.Query(json);
			JSONArray arr = (JSONArray)resultJSON1.get("Content");
			for(int i = 0; i < arr.size(); i++){
				dbTableLst.add(OssUtils.getProperty("database.name") + arr.get(i).toString());
			}
			arr = (JSONArray)resultJSON2.get("Content");
			for(int i = 0; i < arr.size(); i++){
				dbTableLst.add(OssUtils.getProperty("fjd.database.name") + arr.get(i).toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		String fileName = "tableSchema.txt";
		if(OssUtils.getProperty("relationDb.use") != null && OssUtils.getProperty("relationDb.use").equalsIgnoreCase("true")){
			fileName = "tableSchemaSql.txt";
		}

		InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName);
		BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
		String jsonBody = "";
		String line;
		try {
			line = reader.readLine();
			while (line != null) {
				if (line.trim().startsWith("//")) {
					if (!jsonBody.trim().isEmpty()) {
						json = JSONObject.parseObject(jsonBody);
						if(json.getString("Database").equalsIgnoreCase("not_this_db")){
							json.put("Database", OssUtils.getProperty("fjd.database.name"));
						}else{
							json.put("Database", OssUtils.getProperty("database.name"));
						}
						if(!dbTableLst.contains(json.get("Database").toString() + json.get("Datatable").toString())){
							log.info(json.toString());
							try {
								JSONObject result = agent.Query(json);
								log.info(result.toString());
							}catch (Exception e) {
								log.error(e.getMessage());
								e.printStackTrace();
							}
						}

						jsonBody = "";
					}
				} else {
					jsonBody = jsonBody + line;
				}
				line = reader.readLine();
			}
			json = JSONObject.parseObject(jsonBody);
			if(json.getString("Database").equalsIgnoreCase("not_this_db")){
				json.put("Database", OssUtils.getProperty("fjd.database.name"));
			}else{
				json.put("Database", OssUtils.getProperty("database.name"));
			}
			if(!dbTableLst.contains(json.get("Database").toString() + json.get("Datatable").toString())){
				log.info(json.toString());
				JSONObject result = agent.Query(json);
				log.info(result.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private void createDb(){
		boolean isExist = false;
		String jsonStr = "{\"QueryType\":\"database_list\"}";
		JSONObject json = JSONObject.parseObject(jsonStr);
		JSONObject resultJSON = null;
		try {
			resultJSON = agent.Query(json);
		} catch (Exception e) {
			e.printStackTrace();
		}
		JSONArray arr = (JSONArray)resultJSON.get("Content");
		createDatabasePublic(arr);
		for(int i = 0; i < arr.size(); i++){
			if (arr.get(i).toString().equals(OssUtils.getProperty("database.name"))){
				isExist = true;
				break;
			}
		}
		if(isExist){
			return;
		}
		try {
			agent.NDL_AddDatabase(OssUtils.getProperty("database.name"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * description 创建db_public能耗数据库
	 * @param dbList 数据库列表
	 * @return void
	 * @author feng
	 * @since 11:46 2018/7/3
	 */
	private void createDatabasePublic(JSONArray dbList) {
		boolean isExist = false;
		if (dbList == null || dbList.size() == 0) {
			return;
		}
		for (int i = 0; i < dbList.size(); i++) {
			if (dbList.get(i).toString().equals(OssUtils.getProperty("fjd.database.name"))) {
				isExist = true;
				break;
			}
		}

		if (isExist) {
			return;
		}
		try {
			agent.NDL_AddDatabase(OssUtils.getProperty("fjd.database.name"));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
