'use strict';

const fs = require('fs');
const log = require('../logger');

const LVGL_CMD_FIFO = process.env.CLAWD_LVGL_CMD_FIFO || '/tmp/lvgl_cmd';

function writeLvglCommand(command) {
  try {
    const fd = fs.openSync(LVGL_CMD_FIFO, fs.constants.O_WRONLY | fs.constants.O_NONBLOCK);
    fs.writeSync(fd, `${command}\n`);
    fs.closeSync(fd);
    return true;
  } catch (e) {
    log.warn('display', `lvgl cmd failed (${command}): ${e.message}`);
    return false;
  }
}

class BasicLed {
  constructor(name) {
    this.name = name;
    this._current = null;
  }
  on() { this._current = 'on'; log.debug('led', `[rk3588-lvgl] ${this.name} on`); }
  off() { this._current = 'off'; log.debug('led', `[rk3588-lvgl] ${this.name} off`); }
  blink() { this._current = 'blink'; log.debug('led', `[rk3588-lvgl] ${this.name} blink`); }
  destroy() { this._current = 'off'; log.debug('led', `[rk3588-lvgl] ${this.name} destroy`); }
}

class StatusLed {
  setSetup() { log.debug('led', '[rk3588-lvgl] status setup'); }
  setApps() { log.debug('led', '[rk3588-lvgl] status apps'); }
  off() { log.debug('led', '[rk3588-lvgl] status off'); }
}

class Display {
  showAP() {
    if (writeLvglCommand('show_ap')) {
      log.info('display', '显示屏 → AP（闪烁）');
    }
  }

  showConn() {
    if (writeLvglCommand('show_conn')) {
      log.info('display', '显示屏 → Conn（闪烁）');
    }
  }

  showErr0() {
    if (writeLvglCommand('show_err0')) {
      log.info('display', '显示屏 → Err0');
    }
  }

  showTime() {
    if (writeLvglCommand('show_time')) {
      log.info('display', '显示屏 → 时间');
    }
  }

  showPin(pin) {
    const s = String(pin || '').padStart(4, '0').slice(-4);
    if (writeLvglCommand(`show_pin:${s}`)) {
      log.info('display', `显示屏 → PIN: ${s}（闪烁）`);
    }
  }
}

class LanLed {
  start() { log.debug('led', '[rk3588-lvgl] LAN start ignored'); }
  stop() { log.debug('led', '[rk3588-lvgl] LAN stop ignored'); }
}

const led = new BasicLed('wifi');
led.bt = new BasicLed('bt');
led.status = new StatusLed();
led.display = new Display();
led.lan = new LanLed();

module.exports = led;
