package net.northking.cctp.upperComputer.controller;

import cn.hutool.core.date.StopWatch;
import com.alibaba.fastjson.JSONObject;
import io.appium.java_client.AppiumDriver;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import net.northking.cctp.upperComputer.constants.UpperComputerConstant;
import net.northking.cctp.upperComputer.deviceManager.IOSDeviceManager;
import net.northking.cctp.upperComputer.entity.DebuggerDeviceInfo;
import net.northking.cctp.upperComputer.entity.PhoneEntity;
import net.northking.cctp.upperComputer.service.DebuggerService;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.WebElement;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/engine")
@Api(tags = "上位机获取引擎信息控制器")
public class EngineController {

    private final Logger logger = LoggerFactory.getLogger(EngineController.class);

    @Resource(name = "androidService")
    private DebuggerService androidService;

    @Resource(name = "iosService")
    private DebuggerService iosService;


    @ApiOperation(value = "获取设备驱动")
    @PostMapping("/getDriver")
    public AppiumDriver<WebElement> getDeviceDriver(@RequestBody DebuggerDeviceInfo info){
        AppiumDriver<WebElement> driver = null;
        logger.info("get device[{}] driver.............",info.getDeviceId());
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            driver = iosService.getDriver(info);
        } else {
            driver = androidService.getDriver(info);
        }
        return driver;
    }

    @ApiOperation(value = "初始化App")
    @PostMapping("/initApp")
    public boolean initApp(@RequestBody DebuggerDeviceInfo info){
        boolean result;
        logger.info("init app[{}] in device[{}],reinstall==>{},cleanData===>{}",info.getAppPackage(),info.getDeviceId(),info.isReInstall(),info.isCleanData());
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            result = iosService.initApp(info);
        } else {
            result = androidService.initApp(info);
        }
        return result;
    }

    @ApiOperation(value = "回收设备")
    @GetMapping("/destroyDriver/{type}/{deviceId}")
    public boolean destroyDriver(@PathVariable("deviceId")String deviceId,@PathVariable("type")String type){
        boolean result;
        logger.info("destroy driver in device[{}]...............",deviceId);
        if (UpperComputerConstant.IOS.equals(type)) {
            result = iosService.destroyDriver(deviceId);
        } else {
            result = androidService.destroyDriver(deviceId);
        }
        return result;
    }

    /**
     * 截区域上传文件服务器
     * @param info
     * @return
     */
    @ApiOperation(value = "截区域上传文件服务器")
    @PostMapping("/getScreenShot")
    public String getScreenShot(@RequestBody DebuggerDeviceInfo info){
        String result = null;
        logger.info("screen shot in device[{}]...............",info.getDeviceId());
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            result = iosService.getScreenShot(info);
        } else {
            result = androidService.getScreenShot(info);
        }
        return result;
    }

    /**
     * 截全屏返回base64
     * @param info
     * @return
     */
    @ApiOperation(value = "截全屏返回base64")
    @PostMapping("/shotAllScreen")
    public String shotAllScreen(@RequestBody DebuggerDeviceInfo info){
        logger.info("screen shot in device[{}]...............",info.getDeviceId());
        String allScreenBase64 = null;
        if ("0".equals(info.getPlatform())) {
            allScreenBase64 = androidService.shotAllScreen(info);
        } else if ("1".equals(info.getPlatform())) {
            allScreenBase64 = iosService.shotAllScreen(info);
        }
        return allScreenBase64;
    }

    /**
     * 截全屏上传文件服务器，租户id
     * @param info
     * @return
     */
    @ApiOperation(value = "截全屏上传文件服务器")
    @PostMapping("/uploadShotAllScreen")
    public String uploadShotAllScreen(@RequestBody DebuggerDeviceInfo info){
        logger.info("screen shot and upload in device[{}]...............",info.getDeviceId());
        String path = null;
        if ("0".equals(info.getPlatform())) {
            path = androidService.uploadShotAllScreen(info);
        } else if ("1".equals(info.getPlatform())) {
            path = iosService.uploadShotAllScreen(info);
        }
        return path;
    }

    /**
     * 截区域返回base64
     * @param info
     * @return
     */
    @ApiOperation(value = "截区域返回base64")
    @PostMapping("/getScreenShotToBase64")
    public String getScreenShotToBase64(@RequestBody DebuggerDeviceInfo info){
        String result = null;
        logger.info("screen shot in device[{}]...............",info.getDeviceId());
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            result = iosService.getScreenShotToBase64(info);
        } else {
            result = androidService.getScreenShotToBase64(info);
        }
        return result;
    }

    @ApiOperation(value = "android清除数据")
    @PostMapping("/cleanData")
    public boolean cleanData(@RequestBody DebuggerDeviceInfo info){
        return androidService.cleanData(info.getDeviceId(), info.getAppPackage());
    }

    @ApiOperation(value = "获取包版本")
    @PostMapping("/getPackageVersion")
    public String getPackageVersion(@RequestBody DebuggerDeviceInfo info){
        String version = "";
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            version = iosService.getPackageVersion(info.getDeviceId(), info.getAppPackage());
        } else {
            version = androidService.getPackageVersion(info.getDeviceId(), info.getAppPackage());
        }
        return version;
    }

    @ApiOperation(value = "下载App")
    @PostMapping("/downloadApp")
    public String downloadApp(@RequestBody DebuggerDeviceInfo info){
        return androidService.downloadApp(info.getAppId(),info.getAppName());
    }

    @ApiOperation(value = "开始记录")
    @PostMapping("/startRecord")
    public boolean startRecord(@RequestBody DebuggerDeviceInfo info){
        boolean result = false;
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            result = iosService.startRecord(info);
        } else {
            result = androidService.startRecord(info);
        }
        return result;
    }

    @ApiOperation(value = "结束记录")
    @PostMapping("/endRecord")
    public String endRecord(@RequestBody DebuggerDeviceInfo info){
        String result = null;
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            result = iosService.endRecord(info);
        } else {
            result = androidService.endRecord(info);
        }
        return result;
    }

    /**
     * ios是否安装某一个包
     * @param info
     * @return
     */
    @ApiOperation(value = "ios是否安装某一个包")
    @PostMapping("/isAppInstalled")
    public boolean isAppInstalled(@RequestBody DebuggerDeviceInfo info){
        return iosService.isAppInstalled(info.getDeviceId(), info.getAppPackage());
    }

    /**
     * 移除ios某一个包
     * @param info
     * @return
     */
    @ApiOperation(value = "移除ios某一个包")
    @PostMapping("/removeApp")
    public boolean removeApp(@RequestBody DebuggerDeviceInfo info){
        return iosService.removeApp(info.getDeviceId(), info.getAppPackage());
    }

    /**
     * 安装ios某一个包
     * @param info
     * @return
     */
    @ApiOperation(value = "安装ios某一个包")
    @PostMapping("/installApp")
    public boolean installApp(@RequestBody DebuggerDeviceInfo info){
        boolean result = false;
        int times = 0;
        while (times < 3) {
            if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
                result = iosService.installApp(info.getDeviceId(), info.getAppPath());
            } else {
                result = androidService.installApp(info.getDeviceId(), info.getAppPath());
            }
            if (result) {
                break;
            }
            times ++;
        }
        return result;
    }

    @ApiOperation(value = "激活App")
    @PostMapping("/activeApp")
    public boolean activeApp(@RequestBody DebuggerDeviceInfo info) throws Exception{
        boolean success = false;
        if (StringUtils.isBlank(info.getAppPackage())) {
            throw new Exception("激活App包名不能为空！");
        }
        if (UpperComputerConstant.ANDROID.equals(info.getPlatform())) {
            success = androidService.activeApp(info.getDeviceId(),info.getAppPackage());
        } else {
            success = iosService.activeApp(info.getDeviceId(), info.getAppPackage());
        }
        return success;
    }

    @ApiOperation(value = "执行shell")
    @PostMapping("/execShell")
    public String execShell(@RequestBody DebuggerDeviceInfo info){
        return androidService.execShellWaitResult(info.getShell(),info.getDir(),info.getEnvMap(),info.isWaitOrNot());
    }

    @ApiOperation(value = "获取当前信息")
    @PostMapping("/getCurrentMessage")
    public String getCurrentMessage(@RequestBody DebuggerDeviceInfo info){
        return androidService.getCurrentMessage(info.getDeviceId());
    }

    @ApiOperation(value = "记录设备的请求")
    @PostMapping("/recordDevicePer")
    public boolean recordDevicePer(@RequestBody DebuggerDeviceInfo info){
        logger.info("收到设备【{}】记录性能的请求，caseId:【{}】",info.getDeviceId(),info.getCaseId());
        boolean result = false;
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            result = iosService.recordDevicePer(info);
        } else {
            result = androidService.recordDevicePer(info);
        }
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        logger.info("设备【{}】开启记录性能时间：【{}】ms，caseId:【{}】",info.getDeviceId(),totalTimeMillis,info.getCaseId());
        return result;
    }

    @ApiOperation(value = "结束设备性能的请求")
    @PostMapping("/stopRecordDevicePer")
    public String[] stopRecordDevicePer(@RequestBody DebuggerDeviceInfo info){
        logger.info("收到设备【{}】结束性能的请求，caseId:【{}】",info.getDeviceId(),info.getCaseId());
        String[] result = new String[2];
        if (UpperComputerConstant.IOS.equals(info.getPlatform())) {
            result = iosService.stopRecordDevicePer(info);
        } else {
            result = androidService.stopRecordDevicePer(info);
        }
        return result;
    }

    @ApiOperation(value = "获取窗口")
    @PostMapping("/getWindowsScale")
    public JSONObject getWindowsScale(@RequestBody DebuggerDeviceInfo info){
        JSONObject object = new JSONObject();
        PhoneEntity phoneEntity = IOSDeviceManager.getInstance().getPhoneEntity(info.getDeviceId());
        if (null != phoneEntity) {
            object.put("width", phoneEntity.getScreenWidth());
            object.put("height", phoneEntity.getScreenHeight());
            object.put("scale", phoneEntity.getScale());
        }
        return object;
    }

    @ApiOperation(value = "关闭App")
    @PostMapping("/terminateApp")
    public boolean terminateApp(@RequestBody DebuggerDeviceInfo info){
        return iosService.terminateApp(info.getDeviceId(), info.getAppPackage());
    }

    @PostMapping("/releaseAdbForwardPort")
    public boolean releaseAdbForwardPort(@RequestBody DebuggerDeviceInfo info){
        return androidService.releaseAdbForwardPort(info.getDeviceId());
    }

}
