import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import Modal from 'react-modal'
import ReusableImages from './reusable-images'
import Admin from './../admin'
import Instance from './util/instance'
import { COLORS } from './helpers/colors'
import { ReusableImagesModalStyles } from './helpers/modal-styles'
import { fetchEntity, fetchEntities, createEntity, updateEntity, deleteEntity } from '../actions/index'

interface ObjectNewProps {
  contentDownloads: any[];
  createEntity: any;
  errors: string[];
  eventSeries: any[];
  fetchEntity: any;
  fields: any[];
  instances: any;
  objects: any[];
  successCallback: any;
  template: any;
  transcripts: any[];
  updateModalHeight: any;
}

interface ObjectNewState extends ComponentState {
  contentDownloads: any[];
  errors: string[];
  eventSeries: any[];
  fields: any[];
  files: {};
  images: any;
  instances: any;
  object: any;
  reusableImagesModalOpen: boolean;
  reusableImagesFieldId: number;
  template: any;
  transcripts: any[];
}

class ObjectNew extends React.Component<ObjectNewProps, ObjectNewState> {

  constructor(props) {
    super(props);
    this.state = {
      fetching: true,
      contentDownloads: [],
      errors: [],
      eventSeries: [],
      images: {},
      instances: {},
      fields: [],
      files: {},
      object: {},
      reusableImagesModalOpen: false,
      reusableImagesFieldId: null,
      template: {},
      transcripts: []
    };
  }

  componentDidMount() {
    let pathDirectories = window.location.pathname.split('/');
    this.props.fetchEntity({
      id: pathDirectories[pathDirectories.length - 2],
      directory: "templates",
      entityName: "template"
    }).then(() => {
      let fields = this.props.fields;
      this.props.updateModalHeight(fields);
      let [object, images, files] = this.createEmptyFields(fields, this.props.instances);
      this.setState({
        fetching: false,
        object,
        fields,
        files,
        images,
        instances: this.props.instances,
        template: this.props.template
      }, () => {
        Instance.fetchAdditionalNeededData.call(this, { entityName: 'object', addingEntity: true });
      });
    });
  }

  createEmptyFields(fields, instances) {
    let object = {};
    let images = {};
    let files = {};
    fields.forEach(field => {
      if (field.fieldType == 'color') {
        object[field.id] = Object.values(COLORS)[0];
      } else if (field.fieldType == 'dropdown') {
        object[field.id] = field.menuOptions[0].value;
      } else if (field.fieldType == 'object') {
        object[field.id] = instances[field.id][0].id;
      } else {
        object[field.id] = '';
      }
      if (field.fieldType === 'image') {
        images[field.id] = { url: '', reusability: false };
      }
      if (field.fieldType === 'file') {
        files[field.id] = { url: '' };
      }
    });
    return [object, images, files];
  }

  selectReusableImage(uploadId, url) {
    let fieldId = this.state.reusableImagesFieldId;
    let object = this.state.object;
    object[fieldId] = uploadId;
    let images = this.state.images;
    let image = images[fieldId];
    image['url'] = url;
    image['reusability'] = true;
    this.setState({
      object,
      images
    });
  }

  clickSave() {
    this.setState({
      fetching: true,
    });
    let fieldValuesObject = this.getFormFieldValues();
    this.props.createEntity({
      directory: 'objekts',
      entityName: 'objekt',
      entity: {
        templateId: this.state.template.id
      },
      additionalData: {
        fields: fieldValuesObject
      }
    }).then((response) => {
      this.props.successCallback(this.props.objects);
    }, () => {
      this.setState({
        fetching: false,
        errors: this.props.errors
      });
    });
  }

  getFormFieldValues() {
    let fields = {};
    this.state.fields.forEach(field => {
      fields[field.id] = this.state.object[field.id];
    });
    return fields;
  }

  changeFieldArgs() {
    return {
      thing: 'object',
      errorsArray: this.state.errors
    }
  }

  render() {
    return(
      <div id="object-new" className="admin-modal">
        <div className="component">
          <div className="white-box" style={ { minHeight: 121 } }>
            { Admin.renderSpinner(this.state.fetching) }
            { Admin.renderGrayedOut(this.state.fetching) }
            { Instance.renderFields.call(this, {
              fields: this.state.fields,
              entityName: 'object'
            }) }
            { this.renderAddButton() }
          </div>
        </div>
        <Modal isOpen={ this.state.reusableImagesModalOpen } onRequestClose={ Admin.closeModals.bind(this) } contentLabel="Modal" style={ ReusableImagesModalStyles }>
          <ReusableImages
            entityName="object"
            closeModal={ () => this.setState({ reusableImagesModalOpen: false }) }
            receiveReusableImageFunction={ this.selectReusableImage.bind(this) }
          />
        </Modal>
      </div>
    );
  }

  renderAddButton() {
    if (this.state.fields.length > 0) {
      return(
        <a className={ "orange-button standard-button-width btn" + Admin.renderDisabledButtonClass(this.state.fetching) } onClick={ this.clickSave.bind(this) }>
          { `Add ${this.state.template.name}` }
        </a>
      );
    } else {
      return null;
    }
  }
}

const mapStateToProps = (reducers, props) => {
  return reducers.standardReducer;
};

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ fetchEntity, fetchEntities, createEntity, updateEntity, deleteEntity }, dispatch);
}

export default connect(mapStateToProps, mapDispatchToProps)(ObjectNew);
