import React from 'react';
import { connect } from 'react-redux';
import EasyGUI, { Utils } from '@easyv/react-gui';
import { updateScreenConfig } from 'models/screen';

const { updateArrayConfig } = Utils;

function State({
  isFirstState,
  config = [],
  updateScreenConfig
}: {
  isFirstState: boolean;
  config: any;
  updateScreenConfig: (param) => any;
}) {
  const resultConfig = isFirstState ? config.filter((d) => d._name !== 'initLoad') : config;

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

  return <EasyGUI config={resultConfig} flat={false} onFieldsChange={handleChange} />;
}

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

  if (screen) {
    config = screen.config;
    const panelId = screen.panelId;
    const panel = panelsById[panelId];
    if (panel) {
      isFirstState = panel.states[0] === id;
    }
  }

  return {
    config: config,
    isFirstState: isFirstState
  };
};

const mapDispatchToProps = {
  updateScreenConfig
};

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