// vim: set ts=2 sw=2 et tw=80:

import React, { Component } from "react";
import { Grid } from "semantic-ui-react";
import { editButtonStyle, panelStyle } from "./devices/styleComponents";
import { checkMaxLength, DEVICE_NAME_MAX_LENGTH } from "./devices/constants";
import DeviceType from "./devices/DeviceTypeController";
import NewDevice from "./devices/NewDevice";
import SettingsModal from "./devices/SettingsModal";
import { call } from "../../client_server";

export default class DevicePanel extends Component {
  constructor(props) {
    super(props);
    this.state = {
      editMode: false,
    };

    this.addDevice = this.addDevice.bind(this);
  }

  editModeController = (e) =>
    this.setState((prevState) => ({ editMode: !prevState.editMode }));

  openModal = (settingsDeviceId) => {
    this.setState((prevState) => ({
      openSettingsModal: !prevState.openSettingsModal,
      settingsDeviceId: settingsDeviceId,
    }));
  };

  changeDeviceData = (deviceId, newSettings) => {
    console.log(newSettings.name, " <-- new name --> ", deviceId);
    this.props.devices.map((device) => {
      if (device.id === deviceId) {
        for (let prop in newSettings) {
          if (device.hasOwnProperty(prop)) {
            if (prop === "name") {
              if (checkMaxLength(newSettings[prop])) {
                device[prop] = newSettings[prop];
              } else {
                alert(
                  "Name must be less than " +
                    DEVICE_NAME_MAX_LENGTH +
                    " characters."
                );
              }
            } else {
              device[prop] = newSettings[prop];
            }
          }
        }
      }
      return null;
    });
    this.forceUpdate();
  };

  getDevices = () => {
    if (this.props.activeItem === -1) {
      call
        .getAllDevices()
        .then((res) => {
          if (res.status === 200) {
            this.setState({
              devices: res.data,
            });
          }
        })
        .catch((err) => {
          console.log(err);
        });
    } else {
      call
        .getAllDevicesByRoom(this.props.activeItem)
        .then((res) => {
          if (res.status === 200) {
            this.setState({
              devices: res.data,
            });
          }
        })
        .catch((err) => {});
    }
  };

  async addDevice(data) {
    const ds = await this.props.addDevice(data);
    this.setState({
      devices: ds,
    });
    this.forceUpdate();
  }

  updateDevice = (data) => {
    const roomId = this.props.devices.filter(
      (d) => d.id === this.state.settingsDeviceId
    )[0].roomId;
    data["id"] = this.state.settingsDeviceId;
    data["roomId"] = roomId;
    call
      .deviceUpdate(data)
      .then((res) => {
        if (res.status === 200) {
          this.getDevices();
          this.forceUpdate();
        }
      })
      .catch((err) => {});
  };

  removeDevice = () => {
    const item = this.props.devices.filter(
      (d) => d.id === this.state.settingsDeviceId
    )[0];
    const data = {
      device: item.kind,
      id: this.state.settingsDeviceId,
    };

    call
      .deviceDelete(data)
      .then((res) => {
        if (res.status === 200) {
          this.openModal();
          this.getDevices();
          this.forceUpdate();
        }
      })
      .catch((err) => {});
  };

  render() {
    const edit = {
      mode: this.state.editMode,
      openModal: this.openModal,
    };
    const ds = this.state.devices ? this.state.devices : this.props.devices;
    return (
      <div style={panelStyle}>
        <button style={editButtonStyle} onClick={this.editModeController}>
          Edit
        </button>
        <Grid doubling columns={4} divided="vertically">
          {this.state.openSettingsModal ? (
            <SettingsModal
              openModal={this.openModal}
              updateDevice={this.updateDevice}
              removeDevice={this.removeDevice}
              device={ds.filter((d) => d.id === this.state.settingsDeviceId)[0]}
            />
          ) : (
            ""
          )}
          {ds
            ? ds.map((e, i) => {
                return (
                  <Grid.Column key={i}>
                    <DeviceType
                      updateDev={this.props.updateDeviceUi}
                      type={e.kind}
                      onChangeData={this.changeDeviceData}
                      device={e}
                      edit={edit}
                    />
                  </Grid.Column>
                );
              })
            : null}
          {this.props.activeItem !== -1 ? (
            <Grid.Column>
              <NewDevice addDevice={this.addDevice} devices={ds} />
            </Grid.Column>
          ) : null}
        </Grid>
      </div>
    );
  }
}
