"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.ChecklistEditForm = void 0;

var _preact = require("preact");

var _crate = require("./crate");

var _listTextareaField = require("./list-textarea-field");

var _button = require("./button");

class ChecklistEditForm extends _preact.Component {
  constructor(props) {
    super(props);
    const value = props.value || null;
    this.state = {
      state: value ? 'loaded' : 'idle',
      originalData: null,
      hasChanged: false,
      value
    };
    this.onInput = this.onInput.bind(this);
    this.onSave = this.onSave.bind(this);
  }

  componentDidMount() {
    const {
      onFetch
    } = this.props;

    if (onFetch) {
      this.setState({
        state: 'loading'
      });
      onFetch().then(list => {
        this.receiveList(list);
      });
    }
  }

  receiveList(list) {
    const asString = list.join('\n');
    this.setState({
      state: 'loaded',
      originalData: asString,
      value: list,
      hasChanged: false
    });
  }

  onInput(updatedArray) {
    const hasChanged = updatedArray.join('\n') !== this.state.originalData;
    this.setState({
      hasChanged,
      value: updatedArray
    });
  }

  onSave() {
    this.setState({
      state: 'saving'
    });
    this.props.onSave(this.state.value).then(updated => {
      this.receiveList(updated);
      this.setState({
        state: 'saved'
      });
    });
  }

  render() {
    const {
      name,
      label,
      subLabel,
      onCancel
    } = this.props;
    const {
      state,
      value,
      hasChanged
    } = this.state;
    return (0, _preact.h)("div", {
      "data-e2e": "".concat(name, "Container")
    }, state === 'saving' && (0, _preact.h)(_crate.MessagePageCrate, {
      "data-e2e": "savingMessage",
      loading: true
    }, "Saving updated list..."), state === 'loading' && (0, _preact.h)(_crate.MessagePageCrate, {
      noShadow: true,
      loading: true
    }, "Loading..."), state === 'saved' && (0, _preact.h)(_crate.MessagePageCrate, {
      "data-e2e": "savedMessage",
      success: true
    }, "\"", label, "\" saved"), (state === 'loaded' || state === 'saved') && (0, _preact.h)("div", null, (0, _preact.h)(_listTextareaField.ListTextareaField, {
      updateValue: this.onInput,
      "data-e2e": "".concat(name, "Field"),
      item: {
        name,
        label,
        subLabel,
        required: false,
        value
      }
    }), (0, _preact.h)("div", {
      className: "mt2"
    }, (0, _preact.h)(_button.Button, {
      className: "mr2",
      primary: true,
      large: true,
      "data-e2e": "".concat(name, "SaveButton"),
      disabled: !hasChanged || !value.length,
      onClick: this.onSave
    }, "Save ", label), onCancel && (0, _preact.h)(_button.Button, {
      large: true,
      "data-e2e": "".concat(name, "CancelButton"),
      onClick: onCancel
    }, "Cancel"))));
  }

}

exports.ChecklistEditForm = ChecklistEditForm;