import React from 'react'
import FieldIndexItem from '../field-index-item'
import { TemplateSaveButton } from '../_template-save-button'
import Admin from '../../admin'

const Template = {

  clickAddField() {
    const fields = Template.getUpdatedFieldsArray.call(this);
    this.setState({
      fields: fields.concat({ ...Template.emptyField() }),
      errors: {
        ...this.state.errors,
        fields: this.state.errors.fields.concat([[]])
      }
    });
  },

  clickTrash(row) {
    this.setState({
      fields: this.state.fields.filter((_field, idx) => idx !== row),
      errors: {
        ...this.state.errors,
        fields: Array(this.state.fields.length).fill([])
      }
    });
  },

  convertFieldsToSnakeCase: (fields) => {
    return fields.map((field) => {
      return({
        char_limit: field.charLimit,
        field_type: field.fieldType,
        id: field.id,
        mandatory: field.mandatory,
        menu_options: field.menuOptions,
        name: field.name,
        object_type: field.objectType,
        description: field.description
      });
    });
  },

  emptyField() {
    return(
      {
        id: "",
        frontEndId: Date.now(),
        name: "",
        mandatory: "no",
        fieldType: "text",
        objectType: "",
        charLimit: "0",
        menuOptions: [],
        description: ""
      }
    );
  },

  getUpdatedFieldsArray() {
    let result = [];
    for (let i = 0; i < Object.keys(this.state.fieldRefs).length; i++) {
      if (this.state.fieldRefs[i]) {
        result.push(this.state.fieldRefs[i].reportFullStateToParent());
      }
    }
    return result;
  },

  notifySaveButton(fieldIndex, status) {
    this.state.saveButtonRef.updateSaveStates(fieldIndex, status)
  },

  rearrangeFields(draggedIndex, dropZoneIndex) {
    let fields = Template.getUpdatedFieldsArray.call(this);
    let newFields = [], newFieldErrors = [];
    let field, errorsArray;
    if (dropZoneIndex == -1) {
      field = fields[draggedIndex];
      errorsArray = this.state.errors["fields"][draggedIndex];
      field.order = 0;
      newFields.push(field);
      newFieldErrors.push(errorsArray);
    }
    for (var i = 0; i < fields.length; i++) {
      if (i != draggedIndex) {
        field = fields[i];
        errorsArray = this.state.errors["fields"][i];
        field.order = i;
        newFields.push(field);
        newFieldErrors.push(errorsArray);
      }
      if (i == dropZoneIndex) {
        field = fields[draggedIndex];
        errorsArray = this.state.errors["fields"][draggedIndex];
        field.order = i;
        newFields.push(field);
        newFieldErrors.push(errorsArray);
      }
    }
    let newErrors = this.state.errors;
    newErrors["fields"] = newFieldErrors;
    this.setState({
      fields: newFields,
      errors: newErrors
    }, () => {
      this.setState({
        changesToSave: this.checkForChanges.call(this)
      });
    });
  },

  renderButtons() {
    return(
      <div>
        <TemplateSaveButton
          ref={ (saveButton) => { this.state.saveButtonRef = saveButton } }
          fetching={ this.state.fetching }
          justSaved={ this.state.justSaved }
          clickSave={ this.clickSave.bind(this) }
          fieldOrder={ this.state.fields.map((field) => field.id) }
          fieldOrderSaved={ this.state.fieldsSaved.map((field) => field.id) }
          parentChanges={ this.state.changesToSave }
        />
        { Template.renderViewObjectsLink.call(this) }
        <a className={ "delete-button" + Admin.renderDisabledButtonClass(this.state.fetching) } onClick={ Admin.changeState.bind(this, "deleteModalOpen", true) }>
          Delete
        </a>
      </div>
    );
  },

  renderFieldsZone(templates) {
    return(
      <div>
        <hr />
        { this.state.fields.map((field, index) => {
          // errors are being passed by reference, removing errors in FieldIndexItem will remove them from parent state as well
          // not sure why it's different for the field object
          return(
            <FieldIndexItem
              key={ field.frontEndId }
              index={ index }
              fetching={ this.state.fetching }
              field={ field }
              errors={ this.state.errors['fields'][index] }
              notifySaveButton={ Template.notifySaveButton.bind(this) }
              clickTrash={ Template.clickTrash.bind(this) }
              renderHandle={ this.state.fields.length > 1 }
              rearrangeFields={ Template.rearrangeFields.bind(this) }
              parentTemplates={ () => { return templates; } }
              ref={ (fieldIndexItem) => { this.state.fieldRefs[index] = fieldIndexItem } }
            />
          );
        }) }
        <a className={ (this.state.fields.length === 0 ? "no-fields " : "") + "green-outline-button" + Admin.renderDisabledButtonClass(this.state.fetching) } onClick={ Template.clickAddField.bind(this) }>
          Add new field
        </a><br />
      </div>
    );
  },

  renderViewObjectsLink() {
    if (this.props.templateName === "template") {
      return(
        <a href={ `/admin/templates/${this.state.template.id}/all` } className="link" id="view-all">View { this.state.savedTemplate.name } List</a>
      );
    } else {
      return null;
    }
  }
};

export default Template;
