package com.bocloud.ims.service.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.commons.lang3.StringUtils;

import com.bocloud.cmp.model.installation.IpmiInfo;
import com.bocloud.common.enums.PostDataFormat;
import com.bocloud.common.http.HttpClient;
import com.bocloud.common.model.Result;
import com.bocloud.ims.common.utils.constant.Constant;

/**
 * 获取jviewer.jnlp
 * 
 * @author 007
 *
 */
public class IpmiRemoteViewer {
    private static Logger logger = LoggerFactory.getLogger(IpmiRemoteViewer.class);

    private static final String LINE_END = "\\n";

    public static String getCookie(IpmiInfo info) {
        try {
            if (!StringUtils.isNotEmpty(info.getHost()) || !StringUtils.isNotEmpty(info.getUser())
                    || !StringUtils.isNotEmpty(info.getPassword())) {
                logger.error("参数异常{}", info.toString());
                return null;
            }
            HttpClient client = new HttpClient(1000 * 10, PostDataFormat.RAW);
            String url = Constant.HTTP_PREFIX + info.getHost() + "/rpc/WEBSES/create.asp?WEBVAR_USERNAME="
                    + info.getUser() + "&WEBVAR_PASSWORD=" + info.getPassword();
            Result result = client.get(url);
            if (result.isFailed()) {
                logger.error("请求ipmi web{}失败,{}", url, result.toString());
                return null;
            }
            for (String line : result.getMessage().split(LINE_END)) {
                if (line.contains("SESSION_COOKIE")) {
                    return line.split("\'")[3];
                }
            }
            logger.error("请求ipmi web{}失败,SESSION_COOKIE不存在,{}", url, result.getMessage());
            return null;
        } catch (Exception e) {
            logger.error("获取cookie失败:", e);
            return null;
        }
    }

}
