import {API, BaseService} from '@bthlabs/homehub-core';
import isEqual from 'lodash/isEqual';

import {kServiceTradfri, kWidgetTradfri} from './defs';

export class TradfriService extends BaseService {
  static kind = kServiceTradfri;
  static widget = kWidgetTradfri;
  static emptyCharacteristics () {
    return {
      host: '',
      key: '',
    };
  }
  async start () {
    const result = await API.Services.start(
      this.kind, this.instance, this.characteristics
    );

    this.notify(result);
  }
  async stop () {
    return API.Services.stop(this.kind, this.instance);
  }
  setCharacteristics (newCharacteristics) {
    const shouldRestart = Object.keys(
      TradfriService.emptyCharacteristics()
    ).some(
      (key) => {
        return !isEqual(this.characteristics[key], newCharacteristics[key]);
      }
    );

    super.setCharacteristics(newCharacteristics);

    if (shouldRestart) {
      this.restart();
    }
  }
  setLightsState = async (lightIds, nextState) => {
    const result = await API.Services.use(
      kServiceTradfri, this.instance, 'set_lights_state', [lightIds, nextState]
    );

    return result;
  }
}
