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.Property;
import org.apache.tapestry5.http.services.Request;
import org.apache.tapestry5.http.services.RequestGlobals;
import org.apache.tapestry5.ioc.annotations.Inject;

import lombok.extern.slf4j.Slf4j;
import net.wicp.tams.app.duckula.controller.BusiTools;
import net.wicp.tams.app.duckula.controller.bean.models.CommonConsumer;
import net.wicp.tams.app.duckula.controller.bean.models.CommonDump;
import net.wicp.tams.app.duckula.controller.bean.models.CommonTask;
import net.wicp.tams.app.duckula.controller.bean.models.CommonVersion;
import net.wicp.tams.app.duckula.controller.config.ConfigItem;
import net.wicp.tams.app.duckula.controller.config.constant.CommandType;
import net.wicp.tams.app.duckula.controller.dao.CommonConsumerMapper;
import net.wicp.tams.app.duckula.controller.dao.CommonDumpMapper;
import net.wicp.tams.app.duckula.controller.dao.CommonTaskMapper;
import net.wicp.tams.app.duckula.controller.dao.CommonVersionMapper;
import net.wicp.tams.app.duckula.controller.service.DeployService;
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.component.response.FileStreamResponse;
import net.wicp.tams.component.services.IReq;

@Slf4j
public class DownLoadHelm3Charts {

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

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

	@Inject
	private DeployService deployService;

	@Inject
	private CommonTaskMapper commonTaskMapper;
	
	@Inject
	private CommonVersionMapper commonVersionMapper;
	
	@Inject
	private CommonDumpMapper commonDumpMapper;
	@Inject
	private CommonConsumerMapper commonConsumerMapper;
	/***
	 * 页面初始化
	 * 
	 * @param type
	 * @param id
	 * @return
	 */
	public Object onActivate(String type, Long id) {
		CommandType commandType = CommandType.valueOf(type);
		// 得到当前的配置文件
		String viewConf = deployService.viewConfK8s(commandType, id,6);
		// 检查源文件
		String baseDirPath = null;
		String parentPath = null;
		try {
			parentPath =IOUtil.mergeFolderAndFilePath(System.getProperty("user.home"),
					"/.tams/tempcharts/" + UUIDGenerator.getUniqueLong());
			baseDirPath = IOUtil.mergeFolderAndFilePath(parentPath,"/duckula-task");
			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"),
							DownLoadHelm3Charts.class));
			Map<String, Object> params = new HashMap<String, Object>();
			CommonVersion commonVersion=null;
			switch (commandType) {
			case task:
				CommonTask commonTask = commonTaskMapper.selectById(id);
				commonVersion = commonVersionMapper.selectById(commonTask.getVersionId());
				break;
			case consumer:
				CommonConsumer commonConsumer = commonConsumerMapper.selectById(id);
				commonVersion = commonVersionMapper.selectById(commonConsumer.getVersionId());
				break;
			case dump:
				CommonDump commonDump = commonDumpMapper.selectById(id);
				commonVersion = commonVersionMapper.selectById(commonDump.getVersionId());
				break;
			default:
				break;
			}
			params.put(ConfigItem.task_version, BusiTools.packVersionImage(commonVersion, true));
			params.put(ConfigItem.task_data_version, BusiTools.packVersionImage(commonVersion, false));
			params.put(ConfigItem.task_image, BusiTools.getImageGroup(commonVersion.getImageGroup()));
			//params.put(ConfigItem.configmap_name, commandType.formateConfigName(selectTask.getName()));			
			params.put(ConfigItem.task_cmd, commandType.getDockerShellFile());			
			params.put(ConfigItem.configmap_filecontext, viewConf);
			
			
			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);
			final String baseJarPath = baseDirPath + ".tar";
			FileStreamResponse retobj = new FileStreamResponse(new File(baseJarPath));					
			return retobj;
		} catch (Exception e) {
			log.error("导出文件失败", e);
			return null;
		} finally {
			try {
				FileUtils.forceDelete(new File(parentPath));
			} 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, DownLoadHelm3Charts.class);
		File toFile = new File(IOUtil.mergeFolderAndFilePath(baseDirPath, path));
		FileUtils.copyInputStreamToFile(inputStream, toFile);
	}
}
