"ui";

// auto.waitFor();

var storage = storages.create("_##_@_DY_Proxy");

ui.layout(
    <vertical padding="16" gravity="center">
        <text id="_id" textSize="28sp" textColor="gray" text="设备号" gravity="center" />
        <text id="id" textSize="28sp" textColor="red" text="" gravity="center" textStyle="bold" bg="#0f0f0f" />
        <text textSize="16sp" textColor="gray" text="点击序列号复制到剪贴板" gravity="center" />
    </vertical>
);

let times = storage.get('__times', 0)
let host = storage.get("__host", "")
log("HOST=", host)
if (host.length == 0) {
    host = "http://10.1.1.108:8080"
    storage.put("__host", host)
}

//指定确定按钮点击时要执行的动作
const deviceID = device.getAndroidId()
// split device per 4 char with -
let __deviceID = deviceID.slice(0, 4) + "-" + deviceID.slice(4, 8) + "-" + deviceID.slice(8, 12) + "-" + deviceID.slice(12, 16)
log(__deviceID)
ui.id.setText(__deviceID)
ui.id.click(() => {
    setClip(__deviceID)
    toast("已复制到剪贴板")
})

//启用按键监听
events.setKeyInterceptionEnabled("volume_up", true);
events.setKeyInterceptionEnabled("volume_down", true);

events.observeKey();
events.observeNotification();

let eventVolumeUp = function (event) {
    toast("音量上键被按下了");
    let lastID = storage.get('__lastID', 0)

    let path = "{host}/api/devices/{deviceID}/follower"
    let url = path.replace("{host}", host).replace("{deviceID}", deviceID)
    if (lastID != 0) {
        url = url + "?lastID=" + lastID
    }
    log("url =", url)

    // let resp = http.get(url)
    // let body = resp.body.json()
    // if (body == null) {
    //     toast("没有新的数据")
    //     return
    // }
    // storage.put('__lastID', body.ID)
    // log("lastID =", storage.get('__lastID', 0))
    // log("body =", body)
}

let eventHandler = {
    volumeUp: eventVolumeUp,
    volumeDown: function (event) {
        toast("音量下键被按下了");
        exit();
    },
    notification: function (n) {
        log("通知时间为:" + new Date(n.when));
        log("应用包名为:" + n.getPackageName());
        log("标题:" + n.getTitle());
        log("内容:" + n.getText());
    }
};

events.onKeyUp("volume_up", eventHandler.volumeUp);
events.onKeyDown("volume_down", eventHandler.volumeDown);
events.on("notification", eventHandler.notification);

// setInterval(() => { log("WORKING...") }, 1000);