import React, { Component } from 'react';
import ConfirmModal from '../../../../components/ConfirmModal';
import FileSelect from '../../../../components/FileSelect';
import ImportAssets from '../../../../components/ImportAssets';
import exportConfig from 'constants/export-config';

const { extension } = exportConfig;

interface IProps {
  children: React.ReactElement;
  onComplete: () => void;
}

interface IState {
  visible: boolean;
  fonts: any[];
}

class ImportFontsModal extends Component<IProps, IState> {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      fonts: []
    };
  }

  showModal = () => {
    this.setState({
      visible: true,
      fonts: []
    });
  };

  onFileSelect = (file) => {
    this.setState((prev) => ({
      fonts: prev.fonts.concat(file)
    }));
  };

  onRemove = (id) => {
    this.setState((prev) => ({
      fonts: prev.fonts.filter((d) => d.uid !== id)
    }));
  };

  hideModal = () => {
    this.setState(
      {
        visible: false,
        fonts: []
      },
      () => {
        this.props.onComplete();
      }
    );
  };

  render() {
    const { visible, fonts } = this.state;

    return (
      <span>
        <span onClick={this.showModal}>{this.props.children}</span>
        <ConfirmModal
          visible={visible}
          title="字体文件导入"
          onClose={this.hideModal}
          onOk={this.hideModal}
          footer={true}
          okText="关闭"
          cancelText={''}
          destroyOnClose>
          <FileSelect accept={[extension.font, '.ttf', '.otf', '.ttc']} onComplete={this.onFileSelect} />
          <div className="import-container">
            {fonts.map((d) => {
              let extname = d.name.slice(d.name.lastIndexOf('.'));
              return <ImportAssets key={d.uid} file={d} assets={['font']} onRemove={this.onRemove} isZip={extname === extension.font} />;
            })}
          </div>
        </ConfirmModal>
      </span>
    );
  }
}

export default ImportFontsModal;
