package com.bocloud.ims.booter.controller.resource.h3c;

import com.alibaba.fastjson.JSONObject;
import com.bocloud.common.annotations.Log;
import com.bocloud.common.enums.BoCloudService;
import com.bocloud.common.model.BocloudResult;
import com.bocloud.common.model.RequestContext;
import com.bocloud.common.utils.Common;
import com.bocloud.ims.interfaces.h3c.H3cCloudServerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;

@RestController
@RequestMapping("/v1/h3c/vms")
@Api(value = "H3c云主机", tags = "H3c云主机")
public class H3cCloudServerController {

	private static Logger logger = LoggerFactory.getLogger(H3cCloudServerController.class);

	@Autowired
	H3cCloudServerService h3cCloudServerService;

	/**
	 * 获取云主机控制台
	 *
	 * @param id
	 * @return
	 */
	@ApiOperation(tags = { "CMC",
			"CSC" }, value = "获取云主机控制台",  httpMethod = "GET")
	@Log(module = BoCloudService.IMS, target = "h3c云主机", operation = "获取云主机控制台")
	@GetMapping("/{id}/console")
	public void console(@PathVariable(Common.ID) Long id, @Value(Common.REQ_CONTEXT) RequestContext context,
			HttpServletResponse response) {
		BocloudResult bocloudResult = h3cCloudServerService.console(id, context.getTarget());
		JSONObject result = JSONObject.parseObject(JSONObject.toJSONString(bocloudResult.getData()));
		String name = result.getString(Common.NAME);
		String jnlpXml = result.getString(Common.VALUE);
		try {
			ServletOutputStream outputStream = response.getOutputStream();
			response.setContentType("application/x-java-jnlp-file");
			response.setHeader("Content-disposition", "inline; filename=" + URLEncoder.encode(name + ".jnlp", "UTF-8"));
			outputStream.write(jnlpXml.getBytes("UTF-8"));
			outputStream.close();
		} catch (Exception e) {
			logger.error("文件下载失败：", e);
		}
	}
}
