import {Widget} from '@bthlabs/homehub-components';
import lodashIsFinite from 'lodash/isFinite';
import {Duration} from 'luxon';
import React from 'react';

import './UptimeWidgetView.scss';

export const UptimeWidgetView = (props) => {
  if (!props.serviceState) {
    return null;
  }

  let uptime = 0;
  if (props.serviceState && lodashIsFinite(props.serviceState.data())) {
    uptime = props.serviceState.data();
  }
  const duration = Duration.fromMillis(uptime * 1000);

  let label = 'second';
  let value = duration.as('seconds');
  if (duration.as('days') > 1) {
    label = 'day';
    value = duration.as('days');
  } else if (duration.as('hours') > 1) {
    label = 'hour';
    value = duration.as('hours');
  } else if (duration.as('minutes') > 1) {
    label = 'minute';
    value = duration.as('minutes');
  }

  value = Math.floor(value);
  if (value !== 1) {
    label += 's';
  }

  return (
    <Widget
      appearance={props.appearance}
      className="UptimeWidgetView"
      instance={props.service.instance}
      kind={props.service.kind}
      layout={props.service.layout}
    >
      <h6>Uptime</h6>
      <h4>{value} {label}</h4>
    </Widget>
  );
};

UptimeWidgetView.defaultLayout = {
  h: 3,
  w: 4,
};
UptimeWidgetView.icon = null;
UptimeWidgetView.layoutConstraints = {
  minH: 3,
  minW: 4,
};
UptimeWidgetView.title = 'Uptime';

export default UptimeWidgetView;
