<script>
import config from "../../managers/config"
import isNumber from "lodash/isNumber"

config.defaults({
  "Space.layout": "horizontal",
  "Space.size": "default",
  "Space.align": "stretch",
})

const SPACE_SIZE = {
  small: 4,
  default: 8,
  medium: 12,
  large: 18,
}

export default {
  name: "mm-space",
  props: {
    layout: {
      type: String,
      default: () => config.get("Space.layout"),
      validator(val) {
        return ["horizontal", "vertical"].includes(val)
      },
    },
    size: {
      type: [String, Number],
      default: () => config.get("Space.size"),
      validator(val) {
        return isNumber(val) || ["large", "default", "medium", "small"].includes(val)
      },
    },
    align: {
      type: String,
      default: () => config.get("Space.align"),
    },
  },
  computed: {
    spaceSize() {
      return isNumber(this.size) ? this.size : SPACE_SIZE[this.size]
    },
    spaceStyle() {
      return {
        [this.layout === "horizontal" ? "margin-right" : "margin-bottom"]: `${this.spaceSize}px`,
      }
    },
  },
  render() {
    const childrenVnode = this.$slots.default ? this.$slots.default.filter(vnode => vnode.tag) : []

    return (<div class={["mm-space", `mm-space__${this.layout}`, {
      [`mm-space__align-${this.align}`]: this.align !== "stretch" },
    ]}>
      {
        childrenVnode.map((child, index) => (
          <div class="mm-space-item" style={(index === childrenVnode.length - 1) ? {} : this.spaceStyle }>
            { child }
          </div>
        ))
      }
    </div>)
  },
}
</script>
