package com.priusis.controller;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.priusis.lib.R;
import com.priusis.util.SysConfigUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * @author yangli
 * @since 2021/09/10
 */
@Validated
@RestController
@RequestMapping(value = "config")
public class ConfigController {

    @GetMapping(value = "get_download_path")
    public R<String> getDownloadPath() throws IOException {
        String path = SysConfigUtil.getProperty("download.path",
                System.getProperty("user.home") + File.separator + "Downloads");
        return R.success(path);
    }

    @PostMapping(value = "save_download_path")
    public R<Void> saveDownloadPath(@RequestBody Map<String, String> params) throws IOException {
        String path = params.get("path");
        SysConfigUtil.saveProperty("download.path", path);
        return R.success();
    }

    @GetMapping(value = "get_device_sn")
    public R<String> getDeviceSN() throws IOException {
        return R.success(SysConfigUtil.getProperty("device.sn"));
    }

    @PostMapping(value = "save_device_sn")
    public R<Void> saveDeviceSN(@RequestBody Map<String, String> params) throws IOException {
        String sn = params.get("sn");
        SysConfigUtil.saveProperty("device.sn", sn);
        return R.success();
    }

    @GetMapping(value = "get_data_reporting")
    public R<JSONArray> getDataReporting() throws IOException {
        return R.success(JSONUtil.parseArray(SysConfigUtil.getProperty("data.reporting",
                "[" +
                        "{\"code\":\"CPU_LOAD\",\"name\":\"CPU负载\",\"frequency\":30}," +
                        "{\"code\":\"CPU_TEMP\",\"name\":\"CPU温度\",\"frequency\":30}," +
                        "{\"code\":\"MAC\",\"name\":\"MAC地址\",\"frequency\":30}," +
                        "{\"code\":\"MEM_CAPACITY\",\"name\":\"内存容量\",\"frequency\":30}" +
                        "]")));
    }

    @PostMapping(value = "save_data_reporting")
    public R<Void> saveDataReporting(@RequestBody JSONArray array) throws IOException {
        SysConfigUtil.saveProperty("data.reporting", array.toString());
        return R.success();
    }
}
