package com.priusis.controller;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.priusis.cache.InstalledProgramCache;
import com.priusis.lib.R;
import com.priusis.util.SysConfigUtil;
import lombok.SneakyThrows;
import org.ini4j.ConfigParser;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

/**
 * @author yangli
 * @since 2021/09/16
 */
@Validated
@RestController
@RequestMapping(value = "remote_control")
public class RemoteControlController {


    @Value(value = "${vnc-repeater}")
    private String vncRepeater;

    @Resource
    private InstalledProgramCache installedProgramCache;

    /**
     * 前端定时任务查询远程控制请求，不为空则表示有请求，展示确认弹窗
     */
    @GetMapping(value = "get_control_request")
    public R<JSONObject> getControlRequest() throws IOException {
        return R.success(JSONUtil.parseObj(SysConfigUtil.getProperty("control.request")));
    }

    /**
     * 接受远程控制请求
     */
    @GetMapping(value = "accept_request")
    public R<Void> acceptRequest() throws IOException, ConfigParser.DuplicateSectionException, ConfigParser.NoSectionException {
        String requestParams = SysConfigUtil.saveProperty("control.request", null);
        if (StrUtil.isBlank(requestParams)) return R.error("无远程请求");
        JSONObject obj = JSONUtil.parseObj(requestParams);
        String id = obj.getStr("id");
        // 设置ID
        String path = installedProgramCache.getPrograms().stream()
                .filter(m -> "UltraVNC".equalsIgnoreCase(m.get("name")))
                .findFirst()
                .map(m -> m.get("path"))
                .orElse(null);
        if (StrUtil.isBlank(path)) return R.error("未安装UltraVNC");
        File file = new File(path + "ultravnc.ini");
        ConfigParser configParser = new ConfigParser();
        configParser.read(file);
        if (!configParser.hasSection("admin")) configParser.addSection("admin");
        configParser.set("admin", "service_commandline",
                StrUtil.format("-autoreconnect ID:{} -connect {} -run", id, vncRepeater));
        configParser.write(file);

        // 重启VNC Server服务
        Runtime.getRuntime().exec("cmd /c net stop uvnc_service");
        Runtime.getRuntime().exec("cmd /c net start uvnc_service");

        // 请求控制的时间，单位分钟
        int minute = obj.getInt("time");
        // 定时任务，指定分钟后执行一次
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @SneakyThrows
            @Override
            public void run() {
                // 停止VNC Server服务
                Runtime.getRuntime().exec("cmd /c net stop uvnc_service");
                timer.cancel();
            }
        }, DateTime.now().offset(DateField.MINUTE, minute));
        return R.success();
    }

    /**
     * 拒绝远程控制请求
     */
    @GetMapping(value = "refuse_request")
    public R<Void> refuseRequest() throws IOException {
        SysConfigUtil.saveProperty("control.request", null);
        return R.success();
    }
}
