package net.wicp.tams.duckula.ops.pages.tools;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.io.FileUtils;
import org.apache.tapestry5.annotations.BeforeRenderTemplate;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.http.services.Request;
import org.apache.tapestry5.http.services.RequestGlobals;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.util.TextStreamResponse;

import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.app.duckula.controller.config.constant.CommandType;
import net.wicp.tams.app.duckula.controller.service.DeployService;
import net.wicp.tams.common.Conf;
import net.wicp.tams.common.apiext.FreemarkUtil;
import net.wicp.tams.common.apiext.IOUtil;
import net.wicp.tams.common.apiext.TarUtil;
import net.wicp.tams.common.apiext.UUIDGenerator;
import net.wicp.tams.common.web.J2EEAssist;
import net.wicp.tams.component.services.IReq;
import net.wicp.tams.component.tools.TapestryAssist;

@Slf4j
public class ViewPodLog {

	@Inject
	protected RequestGlobals requestGlobals;
	@Inject
	protected Request request;
	@Inject
	private IReq req;

	@Property
	private String wsUri;
	@Property
	private String params;

	@Inject
	private DeployService deployService;

	@BeforeRenderTemplate
	public void init() {
		// configName deployid
		String context = Conf.get("common.http.url.context");
		this.wsUri = context.replace(requestGlobals.getHTTPServletRequest().getScheme(), "ws");
		this.wsUri = IOUtil.mergeFolderAndFilePath(this.wsUri, "/websocket");
		String params = request.getParameter("params");
		String[] paramsAry = params.split(":");
		JSONObject json = new JSONObject();
		// commandType taskId deployId
		json.put("commandType", paramsAry[0]);
		json.put("taskId", paramsAry[1]);
		json.put("deployId", paramsAry[2]);
		this.params = json.toJSONString();
	}

	public TextStreamResponse onOldConfig(String type, Long id, Long deployId) {
		String viewConf = deployService.viewConfDeploy(CommandType.valueOf(type), id, deployId);
		// viewConf = viewConf.replaceAll("\\r\\n", "<br/><br/>");
		viewConf = viewConf.replaceAll("\\n", "<br/>");
		return TapestryAssist.getTextStreamResponse(viewConf);
	}

	public TextStreamResponse onNewConfig(String type, Long id, Long deployId) {
		String viewConf = deployService.viewConf(CommandType.valueOf(type), id, deployId);
		viewConf = viewConf.replaceAll("\\r\\n", "<br/>");
		// String retstr = "abc<br/> efc<br/>aaa";
		return TapestryAssist.getTextStreamResponse(viewConf);
	}

	// 下载可以独立布署的helm3 chart包
	public void onTaskDown(String type, Long id) {
		// 得到当前的配置文件
		String viewConf = deployService.viewConfK8s(CommandType.valueOf(type), id);
		viewConf = viewConf.replaceAll("\\r\\n", "<br/>");
		// TODO 替换模板
		// 压缩
		// 检查源文件
		String baseDirPath = null;
		try {
			baseDirPath = IOUtil.mergeFolderAndFilePath(System.getProperty("user.home"),
					"/.tams/tempcharts/" + UUIDGenerator.getUniqueLong());
			File baseDir = new File(baseDirPath);
			if (!baseDir.exists()) {
				baseDir.mkdir();
				copyOriHelm3Charts(baseDirPath, "Chart.yaml");
				copyOriHelm3Charts(baseDirPath, "README.en.md");
				copyOriHelm3Charts(baseDirPath, "README.md");
				// copyOriHelm3Charts(baseDirPath,"values.yaml");
				copyOriHelm3Charts(baseDirPath, "/templates/_helpers.tpl");
				copyOriHelm3Charts(baseDirPath, "/templates/configmap-root.yaml");
				copyOriHelm3Charts(baseDirPath, "/templates/deployment.yaml");
				copyOriHelm3Charts(baseDirPath, "/templates/NOTES.txt");
			}
			String context = IOUtil.slurp(IOUtil.fileToInputStream(
					IOUtil.mergeFolderAndFilePath("/deploy/k8s/duckula-task", "values.yaml"), ViewPodLog.class));
			Map<String, String> params = new HashMap<String, String>();
			String result = FreemarkUtil.getInst().doProcessByTemp(context, params);
			FileUtils.write(new File(IOUtil.mergeFolderAndFilePath(baseDirPath, "values.yaml")), result);
			TarUtil.compress(baseDirPath, baseDirPath + ".tar");
			J2EEAssist.getFileOS(requestGlobals.getHTTPServletResponse(), baseDirPath + ".tar", true);
		} catch (Exception e) {
			log.error("导出文件失败",e);
		} finally {
			try {
				FileUtils.forceDelete(new File(baseDirPath));
				FileUtils.forceDelete(new File(baseDirPath + ".tar"));
			} catch (IOException e) {
				log.error("删除文件失败", e);
			}
		}

	}

	private void copyOriHelm3Charts(String baseDirPath, String path) throws IOException {
		String oriPath = IOUtil.mergeFolderAndFilePath("/deploy/k8s/duckula-task", path);
		InputStream inputStream = IOUtil.fileToInputStream(oriPath, ViewPodLog.class);		
		File toFile = new File(IOUtil.mergeFolderAndFilePath(baseDirPath, path));
		FileUtils.copyInputStreamToFile(inputStream, toFile);
	}

}
