import {Widget} from '@bthlabs/homehub-components';
import {API, BaseService} from '@bthlabs/homehub-core';
import React from 'react';

export const FakeAPIWidgetSettingsView = (props) => {
  const onSpamInputChange = React.useCallback(
    (event) => {
      props.setNextCharacteristics({
        ...props.nextCharacteristics,
        spam: event.target.value
      });
    },
    [props]
  );

  const onEggsInputChange = React.useCallback(
    (event) => {
      props.setNextCharacteristics({
        ...props.nextCharacteristics,
        eggs: event.target.value
      });
    },
    [props]
  );

  if (!props.nextCharacteristics) {
    return null;
  }

  return (
    <React.Fragment>
      <p>
        <label htmlFor="input-spam">Spam</label>
        <input
          type="text"
          value={props.nextCharacteristics.spam}
          onChange={onSpamInputChange}
        />
      </p>

      <p>
        <label htmlFor="input-eggs">Eggs</label>
        <input
          type="text"
          value={props.nextCharacteristics.eggs}
          onChange={onEggsInputChange}
        />
      </p>
    </React.Fragment>
  )
};

export const FakeAPIWidget = (props) => {
  let appearance = {...props.appearance};
  if (props.serviceState !== null) {
    console.log('FakeAPIWidget()', props.serviceState.payload, props.serviceState.isLoading())
    if (props.serviceState.isLoading()) {
      appearance.color = 'blue';
    } else if (props.serviceState.hasError()) {
      appearance.color = 'purple';
    } else if (props.serviceState.hasFatalError()) {
      appearance.color = 'red';
    } else if (props.serviceState.hasData()) {
      appearance.color = 'green';
    }
  }

  return (
    <Widget {...props} appearance={appearance}>
      <p>
        <code>spam: &raquo;{props.service.characteristics['spam']}&laquo;</code>
        <br/>
        <code>eggs: &raquo;{props.service.characteristics['eggs']}&laquo;</code>
      </p>
      <p>
        <code>serviceState: &raquo;{JSON.stringify(props.serviceState)}&laquo;</code>
      </p>
    </Widget>
  );
};

FakeAPIWidget.defaultLayout = {
  h: 6,
  w: 4
};
FakeAPIWidget.layoutConstraints = {
  minH: 6,
  minW: 4
};
FakeAPIWidget.settingsView = FakeAPIWidgetSettingsView;
FakeAPIWidget.title = 'Fake API Service';

export class FakeAPIService extends BaseService {
  static kind = 'FakeAPIService';
  static widget = 'FakeAPIWidget';
  static emptyCharacteristics () {
    return {
      'spam': '',
      'eggs': ''
    };
  }
  async start () {
    const result = await API.Services.start(
      FakeAPIService.kind, this.instance, this.characteristics
    );

    this.notify(result);
  }
  async stop () {
    return API.Services.stop(FakeAPIService.kind, this.instance);
  }
  setCharacteristics (newCharacteristics) {
    super.setCharacteristics(newCharacteristics);
    this.restart()
  }
}
