import { LogManager } from "../LogManager";
import { LogLevel } from '../../common/LogTypes';
import { NetworkService } from "./NetworkService";
import { execSync } from "child_process";

const i2c = require('i2c-bus')
const oled = require('oled-rpi-i2c-bus')
const font = require('oled-font-5x7')
 
var opts = {
    width: 128,
    height: 64,
    address: 0x3C,
    bus: 2,
    driver: 'SSD1306'
};

export class OledService {
    private logger: LogManager;

    private disp: any;
    private i2cBus: any;
    private nwService: NetworkService;

    constructor(logger: LogManager, nwService: NetworkService) {
        this.logger = logger
        this.nwService = nwService
    }

    public init(): void {
        try {
            this.i2cBus = i2c.openSync(2)
            this.disp = new oled(this.i2cBus, opts)
            this.disp.clearDisplay(true)
            
            this.update()
            setInterval(() => this.update(), 1000)
        } catch (err) {
            console.log(err)
            this.logger.log(err, LogLevel.Error, { type: 'OLED', id: '' })
        }
    }

    private update(): void {
        this.disp.clearDisplay(false)

        const ipAddress = this.nwService.GetIpAddress()
        const temperature = execSync('vcgencmd measure_temp | sed s/temp=//g', { encoding: 'utf8' })

        this.disp.setCursor(1, font.height + 1)
        this.disp.writeString(font, 1, 'IP: ' + ipAddress, 1, false)

        this.disp.setCursor(1, 2 * font.height + 1 + font.height * 0.2)
        this.disp.writeString(font, 1, 'Temp. ' + temperature, 1, false)
    }
}
