import _ from "lodash";
import React from "react";
import { connect } from "react-redux";
import { PictureContent } from "./content";

const Content = props => {
  const { actions } = props.settings;

  const haslink = _.get(
    _.filter(
      actions,
      itm =>
        itm.behavior === "click" &&
        (itm.type === "GO_TO_URL" || itm.type === "TRIGGER_NEXT_NODE")
    ),
    0,
    false
  );

  const href = haslink
    ? _.get(
        props.settings,
        "href",
        _.get(props.settings, "actions[0].payload.url", false)
      )
    : false;

  return (
    <PictureContent
      {...props}
      settings={{
        ...props.settings,
        href
      }}
    />
  );
};

const Picture = props => {
  const { settings } = props;

  const marginTop = settings.properties ? settings.properties.marginTop : 0;
  const padding = settings.properties ? settings.properties.padding : 0;
  const textAlign = settings.properties
    ? settings.properties.textAlign
    : "inherit";

  const handleClick = () => {
    const {
      dispatch,
      settings,
      fieldValues,
      updateComponentSettings,
      getComponentSettings
    } = props;
    const { actions } = settings;

    if (actions) {
      const doTheseActions = actions.filter(itm => itm.behavior === "click");
      doTheseActions.forEach(action =>
        dispatch({
          ...action,
          settings: { ...settings, fieldValues },
          updateComponentSettings,
          getComponentSettings
        })
      );
    }
  };

  return (
    <div style={{ marginTop, textAlign }}>
      <div onClick={handleClick} style={{ padding }}>
        <Content {...props} />
      </div>
    </div>
  );
};

export default connect()(Picture);
