import { expect, tap } from '@git.zone/tstest/tapbundle';
import * as plugins from '../../ts/plugins.js';
import { ApcupsdClient } from '../../ts/integrations/apcupsd/index.js';

const statusText = `UPSNAME  : TCP UPS
STATUS   : ONBATT LOWBATT
BCHARGE  : 17.0 Percent
STATFLAG : 0x05000000
`;

tap.test('requests APCUPSd NIS status over local TCP', async () => {
  const server = plugins.net.createServer((socketArg) => {
    socketArg.once('data', (chunkArg) => {
      const buffer = Buffer.isBuffer(chunkArg) ? chunkArg : Buffer.from(chunkArg);
      const length = buffer.readUInt16BE(0);
      const command = buffer.subarray(2, 2 + length).toString('utf8');
      expect(command).toEqual('status');
      socketArg.write(frame(statusText));
      socketArg.write(Buffer.alloc(2));
    });
  });

  await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
  try {
    const address = server.address();
    const port = typeof address === 'object' && address ? address.port : 0;
    const snapshot = await new ApcupsdClient({ host: '127.0.0.1', port, timeoutMs: 1000 }).getSnapshot();
    expect(snapshot.online).toBeTrue();
    expect(snapshot.ups.name).toEqual('TCP UPS');
    expect(snapshot.ups.lineOnline).toBeFalse();
    expect(snapshot.battery.chargePercent).toEqual(17);
  } finally {
    await new Promise<void>((resolve, reject) => server.close((errorArg) => errorArg ? reject(errorArg) : resolve()));
  }
});

const frame = (valueArg: string): Buffer => {
  const payload = Buffer.from(valueArg, 'utf8');
  const result = Buffer.alloc(payload.length + 2);
  result.writeUInt16BE(payload.length, 0);
  payload.copy(result, 2);
  return result;
};

export default tap.start();
