import React from 'react';
import { connect } from 'react-redux';
import { useLocation } from 'react-router-dom';
import EasyGUI, { FormItem, EasyUpload, Utils } from '@easyv/react-gui';
import Dimension from './Dimension';
import ScreenShot from './ScreenShot';
import { updateScreenConfig, updateThumb } from 'models/screen';

const { updateArrayConfig } = Utils;

function Screen({ id, config = [], thumb, updateThumb, updateScreenConfig }) {
  const location = useLocation();

  if (config.length === 0) {
    return null;
  }

  const isDesktopScreen = /\/create\/[0-9]+$/.test(location.pathname);

  const [dimensionConfig, ...restConfig] = config;

  const handleChange = (updates) => {
    updateScreenConfig(updateArrayConfig(config, updates));
  };

  return (
    <>
      <Dimension config={[dimensionConfig]} onChange={handleChange} />
      <EasyGUI config={restConfig} onFieldsChange={handleChange} />
      {isDesktopScreen && (
        <FormItem label="封面">
          <EasyUpload type="uploadImage" value={thumb} onChange={updateThumb} />
          <div style={{ marginTop: 20 }}>
            <ScreenShot id={id} onComplete={updateThumb} />
          </div>
        </FormItem>
      )}
    </>
  );
}

const mapStateToProps = ({ createApp, screensById }) => {
  const { id } = createApp;
  const screen = screensById[id];
  let config;
  let thumb;

  if (screen) {
    config = screen.config;
    thumb = screen.thumb;
  }

  return {
    id,
    config,
    thumb
  };
};

const mapDispatchToProps = {
  updateThumb,
  updateScreenConfig
};

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