import * as React from 'react';
import * as _ from 'lodash';
import {
  textInput,
  selectInput,
  imagePreview
} from './LexSingleInput';
import {
  Card,
  Button
} from 'semantic-ui-react';
const { Box } = require('reflexbox');

const serialize = function(obj: any) {
  var str = [];
  for (var p in obj) {
    if (obj.hasOwnProperty(p)) {
      str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
    }
  }
  return str.join('&');
};

export class LexEdit extends React.Component<any, any> {
  imageRoot = '/png/';
  constructor(props: any) {
    super(props);
    this.state = { lexItem: this.props.lexItem };
  }
  public render() {
    let li = this.state.lexItem;
    let editLang = this.props.fieldMetaMap.lang.get(li);
    let langSelOpts = _.get<any>(this.props.selectionMeta, editLang, []);
    let lexFields = _.keys(this.props.fieldMetaMap).map(field => {
      let fieldMeta = this.props.fieldMetaMap[field];
      let defaultText = fieldMeta.get(li);
      let originalText = fieldMeta.get(this.props.lexItem);
      let options = fieldMeta.options;
      let changed = defaultText !== originalText && this.props.existing;
      let sh = (e: any) => {
        let eventData = {};
        eventData[field] = e.target.value;
        this.handleOnChange(eventData);
      };
      let params = { field, sh, defaultText, options, langSelOpts, changed };
      if (this.props.fieldMetaMap[field].type === 'text') {
        return textInput(params);
      } else if (this.props.fieldMetaMap[field].type === 'select') {
        return selectInput(params);
      } else if (this.props.fieldMetaMap[field].type === 'preview') {
        return imagePreview(params);
      } else {
        console.log('field discarded :', field);
        return null;
      }
    });
    return (
      <Box m={2}>
        <Card raised={true}>
          <Card.Content>
            <Card.Header>
              {_.get<any>(li, 'label', '')}
              <Button
                floated="right"
                icon="download"
                size="tiny"
                onClick={(e, d) => this.handleOnLoad(d)}
              />
              <Button
                floated="right"
                icon="undo"
                size="tiny"
                onClick={(e, d) => this.handleOnUndo(d)}
              />
            </Card.Header>
            <Card.Meta>
              language: {_.get<any>(li, '$.id', '')}
            </Card.Meta>
            <Card.Description>
              {lexFields}
            </Card.Description>
          </Card.Content>
          <Card.Content extra={true}>
            <Button
              basic={true}
              fluid={true}
              color="green"
              onClick={(e, d) => this.handleOnSave(d)}
            >
              Save
            </Button>
          </Card.Content>
        </Card>
      </Box>
    );
  }

  private handleOnUndo(event: any) {
    let lexItem = this.props.lexItem;
    this.setState({ lexItem });
  }

  private handleOnLoad(event: any) {
    // this.props.load(this.state.lexItem)
    let li = this.state.lexItem;
    let word = this.props.fieldMetaMap.label.get(li);
    let pos = this.props.fieldMetaMap.pos.get(li);
    let args = serialize({ word, pos });
    let morphQuery = '/api/morph?' + args;
    fetch(morphQuery)
      .then((response) => response.text())
      .then((jsonMorph) => {
        let morphDict = JSON.parse(jsonMorph);
        let morphMeta = this.props.fieldMetaMap.morphclass;
        let lexItem = morphMeta.set(this.state.lexItem, morphDict.morphclass);
        this.setState({ lexItem });
      })
      .catch((e) => {
        console.log('errored :', e);
      });
  }

  private handleOnChange(event: any) {
    let type = _.keys(event)[0];
    let value = _.values(event)[0] as string;
    let meta = this.props.fieldMetaMap[type];
    let lexItem = meta.set(this.state.lexItem, value);
    this.setState({ lexItem });
  }

  private handleOnSave(event: any) {
    this.props.save(this.state.lexItem);
  }
}
