import { expect, tap } from '@git.zone/tstest/tapbundle';
import { KnxMapper } from '../../ts/integrations/knx/index.js';

const snapshot = KnxMapper.toSnapshot({
  connectionType: 'tunneling_tcp',
  host: '192.168.1.50',
  port: 3671,
  gateway: {
    ip_addr: '192.168.1.50',
    port: 3671,
    name: 'KNX IP Interface',
    supports_tunnelling_tcp: true,
  },
  entities: [
    {
      platform: 'light',
      name: 'Kitchen light',
      entityId: 'light.kitchen_light',
      uniqueId: 'knx_light_kitchen',
      address: '1/1/1',
      brightnessAddress: '1/1/2',
      state: true,
    },
    {
      platform: 'switch',
      name: 'Kitchen outlet',
      address: '1/2/1',
      state: false,
    },
    {
      platform: 'sensor',
      name: 'Kitchen temperature',
      stateAddress: '2/1/1',
      type: 'temperature',
      state: 21.4,
      unit: 'degC',
    },
    {
      platform: 'cover',
      name: 'Living blind',
      moveLongAddress: '3/1/1',
      positionAddress: '3/1/2',
      currentCoverPosition: 75,
    },
    {
      platform: 'climate',
      name: 'Hall thermostat',
      temperatureAddress: '4/1/1',
      targetTemperatureAddress: '4/1/2',
      hvacMode: 'heat',
      targetTemperature: 22,
    },
  ],
});

tap.test('maps KNX group address entities to canonical entities', async () => {
  const entities = KnxMapper.toEntities(snapshot);
  expect(entities.some((entityArg) => entityArg.id === 'light.kitchen_light' && entityArg.state === 'on')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'switch' && entityArg.state === 'off')).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'sensor' && entityArg.state === 21.4)).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'cover' && entityArg.state === 75)).toBeTrue();
  expect(entities.some((entityArg) => entityArg.platform === 'climate' && entityArg.state === 'heat')).toBeTrue();
});

tap.test('maps KNX devices and entity commands', async () => {
  const devices = KnxMapper.toDevices(snapshot);
  const command = KnxMapper.commandForService(snapshot, {
    domain: 'light',
    service: 'turn_on',
    target: { entityId: 'light.kitchen_light' },
    data: { brightness: 128 },
  });
  expect(devices.some((deviceArg) => deviceArg.id.startsWith('knx.interface.'))).toBeTrue();
  expect(command?.telegrams[0].address).toEqual('1/1/2');
  expect(command?.telegrams[0].payload).toEqual(128);
});

tap.test('maps KNX group write and read commands', async () => {
  const writeCommand = KnxMapper.groupWriteCommand(['1/0/1'], true, '1.001');
  const readCommand = KnxMapper.groupReadCommand(['1/0/2']);
  expect(writeCommand?.type).toEqual('group.write');
  expect(writeCommand?.telegrams[0].action).toEqual('write');
  expect(readCommand?.type).toEqual('group.read');
  expect(readCommand?.telegrams[0].action).toEqual('read');
});

export default tap.start();
