package net.northking.cctp.debuger.service;

import lombok.extern.slf4j.Slf4j;
import net.northking.cctp.common.http.ResultWrapper;
import net.northking.cctp.debuger.constants.MobileScriptDebugerConstant;
import net.northking.cctp.debuger.feign.DeviceFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;
@Slf4j
@Service
public class DeviceInfoServiceImpl implements DeviceInfoService{

    private String path;
    @Autowired
    private DeviceFeignClient deviceFeignClient;

    @Override
    public String getEngineAddress(String token) {
        String address = null;
        try {
            ResultWrapper<Map<String, Object>> resultWrapper = deviceFeignClient.getDeviceInfoByToken(token);
            if (resultWrapper.isSuccess()) {
                Map<String, Object> data = resultWrapper.getData();
                Map engineInfo = (Map) data.get(MobileScriptDebugerConstant.ENGINE_INFO);
                if (null != engineInfo) {
                    String ipAddr = (String) engineInfo.get(MobileScriptDebugerConstant.IP_ADDR);
                    if (ipAddr.startsWith("http://")) {
                        ipAddr = ipAddr.replaceAll("http://", "");
                    }
                    String ipPort = (String) engineInfo.get(MobileScriptDebugerConstant.IP_PORT);
                    address = ipAddr + ":" + ipPort;
                }
            }
        } catch (Exception e) {
            log.error("获取引擎失败",e);
            throw new RuntimeException("获取引擎失败");
        }
        return address;
    }

    @Override
    public Boolean exitDeviceUsage(String token) {
        try {
            ResultWrapper<Boolean> resultWrapper = deviceFeignClient.exitDeviceUsage(token);
            if (resultWrapper.isSuccess()) {
                return resultWrapper.getData();
            } else {
                log.warn("设备释放失败，tokenId:{}",token);
            }
        } catch (Exception e) {
            log.warn("设备释放失败，tokenId:{}",token,e);
        }
        return null;
    }

    @Override
    public Map<String, Object> getEngineInfo(String projectId) {
        try {
            ResultWrapper<Map<String,Object>> resultWrapper = deviceFeignClient.getUsageEngine(projectId);
            if (resultWrapper.isSuccess()) {
                return resultWrapper.getData();
            } else {
                log.warn("随机引擎信息获取失败，projectId:{}",projectId);
            }
        } catch (Exception e) {
            log.error("随机引擎信息获取失败，projectId:{}",projectId,e);
        }
        return null;
    }
}
