import React from 'react';
import PropTypes from 'prop-types';
import { Button } from 'reactstrap';
import Dropzone from 'react-dropzone'


class DraftImageDropper extends React.Component {
  static propTypes = {
    url: PropTypes.string.isRequired,
    wsym: PropTypes.string.isRequired,
    curImage: PropTypes.string,
    updateImage: PropTypes.func.isRequired,
  }

  constructor (props) {
    super(props);
    this.state = {
      //draft: new DraftStore(props.draft),
      uploading: false,
    };
  }

  render() {
    let on_drop = (okFiles, ngFiles) => {
      let remove_preview = (file) => window.URL.revokeObjectURL(file.preview);
      let wsym = this.props.wsym;
      
      if (ngFiles)
        ngFiles.forEach(remove_preview);
      if (!okFiles)
        return;
      okFiles.forEach(remove_preview);

      let data = new FormData()
      data.set(`draft[wi_${wsym}]`, okFiles[0]);
      
      this.setState({uploading: true});
      jQuery.ajax({
        url: this.props.url,
        method: 'PATCH',
        contentType: false,
        processData: false,
        data: data,
        success: (data, status, xhr) => {
          this.props.updateImage(wsym, data[`wi_${wsym}_url`]);
          this.setState({uploading: false});
        },
        error: () => alert(I18n.t('upload_err')),
      });
    }

    if (this.state.uploading) {
      return(
        <div className="theme-image">
          <div className="weather-icon-progress" />
        </div>
      );
    }

    var content = <div className="weather-icon-missing">
          <span className="fa fa-plus-circle" />
        </div>;
    if (this.props.curImage) {
      content = <div className="user-weather-icon">
        <img src={this.props.curImage} />
      </div>;
    }
      
    return (
      <div className="theme-image">
        <Dropzone accept="image/*" minSize={128}
                  className="dropzone"
                  activeClassName="dropzone dropzone-active"
                  acceptClassName="dropzone dropzone-accept"
                  rejectClassName="dropzone dropzone-reject"
                  onDrop={on_drop}
                  >
          {content}
          <div className="clearfix"/>
        </Dropzone>
      </div>
    );
  }
}

class DraftEditor extends React.Component {
  static propTypes = {
    draft: PropTypes.object.isRequired,
    wsyms: PropTypes.array.isRequired,
    wsym_rejects: PropTypes.array,
  }

  constructor (props) {
    super(props);
    this.state = {
      //draft: new DraftStore(props.draft),
      draft: Object.assign({}, props.draft),
    };
  }

  updateImage (sym, imageUrl) {
    let d = Object.assign({}, this.state.draft)
    d[`wi_${sym}_url`] = imageUrl;
    this.setState({draft: d})
  }

  updateFrame (value) {
    let d = Object.assign({}, this.state.draft)
    d["day_frame"] = value;
    this.setState({draft: d})
    jQuery.ajax({
      url: d.path,
      method: 'PATCH',
      data: {'draft[day_frame]': value}
    });
  }
  
  render() {
    let d = this.state.draft;

    let header_cols = []
    let wsyms = this.props.wsyms
    wsyms.forEach((ws) => {
      header_cols.push(<th key={`w-h-${ws}`}>
                       {I18n.t('weather_symbols.'+ws)}
                       </th>);
    });
    let body_rows = [
        <tr key="w-r-none">
        <th key="w-ch-none">{I18n.t('none')}</th>
        {wsyms.map((ws) =>
                   <td key={`w-c-none-${ws}`}>
                   <DraftImageDropper key={`i-${ws}`} wsym={ws} url={d.path}
                   curImage={d[`wi_${ws}_url`]} updateImage={this.updateImage.bind(this)} />
                   </td>)}
        </tr>
    ];
    wsyms.forEach((ws1) => {
      let cols = [<th key={`w-ch-${ws1}`}>{I18n.t(`weather_symbols.${ws1}`)}</th>];
      wsyms.forEach((ws2) => {
        var content = null;
        if (ws1 != ws2 && this.props.wsym_rejects && this.props.wsym_rejects.indexOf(ws1+ws2) === -1) {
          content = <DraftImageDropper key={'i-'+ws1+ws2} wsym={ws1+ws2} url={d.path}
          curImage={d[`wi_${ws1}${ws2}_url`]} updateImage={this.updateImage.bind(this)} />
        }
        cols.push(
          <td key={`w-c-${ws1}-${ws2}`}>
            {content}
          </td>);
      });
      body_rows.push(<tr key={`w-r-${ws1}`}>{cols}</tr>);
    });

    return(
      <div className="draft-editor">
        <div className="frame-select">
          <b>{I18n.t('day_frame_type')}:</b>
          <div className="form-check form-check-inline">
            <label className="form-check-label">
              <input className="form-check-input" type="radio" name="frame"
                     checked={d.day_frame == null || d.day_frame == "black"}
                     onClick={() => this.updateFrame('black')}/>
                {I18n.t('day_frames.black')}
            </label>
          </div>
          <div className="form-check form-check-inline">
            <label className="form-check-label">
              <input className="form-check-input" type="radio" name="frame" 
                     checked={d.day_frame == "white"}
                     onClick={(e) => this.updateFrame('white')}/>
                {I18n.t('day_frames.white')}
            </label>
          </div>
        </div>
        <table className={`draft-editor-table day-frame-${d.day_frame}`}>
          <thead>
            <tr>
              <th className="corner">
                <div className="first">{I18n.t('editor_table_header.first_weather')}</div>
                <div className="second">{I18n.t('editor_table_header.second_weather')}</div>
              </th>
              {header_cols}
            </tr>
          </thead>
          <tbody>{body_rows}</tbody>
        </table>
      </div>
    );
  }
}

export default DraftEditor;
