import React from 'react'
import Admin from './../admin'
import isEqual from 'lodash/isEqual';

interface TemplateSaveButtonProps {
  clickSave: any
  fetching: boolean
  fieldOrder: string[]
  fieldOrderSaved: number
  justSaved: boolean
  parentChanges: boolean
}

interface TemplateSaveButtonState extends ComponentState {
  fieldSaveStates: any
}

export class TemplateSaveButton extends React.Component<TemplateSaveButtonProps, TemplateSaveButtonState> {

  constructor(props) {
    super(props);

    this.state = {
      fieldSaveStates: {}
    }
  }

  updateSaveStates(fieldIndex, status) {
    let fieldSaveStates = this.state.fieldSaveStates;
    fieldSaveStates[fieldIndex] = status;
    this.setState({
      fieldSaveStates
    })
  }

  checkForChangesToSave() {
    if (this.props.parentChanges) {
      return true;
    }
    let changes = Object.values(this.state.fieldSaveStates).includes(true);
    if (!changes) {
      changes = !isEqual(this.props.fieldOrder, this.props.fieldOrderSaved);
    }
    return changes;
  }

  resetChangesToSave() {
    this.setState({
      fieldSaveStates: {},
      justSaved: true
    });
  }

  render() {
    let changesToSave = this.checkForChangesToSave();
    let buttonText;
    if (changesToSave) {
      buttonText = 'Save';
    } else {
      buttonText = this.state.justSaved ? 'Saved' : 'No Changes';
    }
    return(
      <a className={ "orange-button standard-button-width btn" + Admin.renderDisabledButtonClass(this.props.fetching || !changesToSave) } onClick={ this.props.clickSave }>
        { buttonText }
      </a>
    );
  }

  componentDidUpdate() {
    if (this.state.justSaved && this.checkForChangesToSave()) {
      this.setState({
        justSaved: false
      });
    }
  }
}
