<script>
import _ from 'lodash';

function applyAutoFormatting(dataType, content) {
  switch (dataType) {
    case 'money':
      if (!_.isNumber(content)) return content;
      const stringVersion = Math.abs(content).toLocaleString('en', {minimumFractionDigits: 2});
      return content < 0 ? `(${stringVersion})` : stringVersion;
    default:
      return content;
  }
}

export default {
  name: 'ElDataTableCell',
  functional: true,
  props: {
    column: { type: Object, required: true },
    rowData: { type: Object, required: true },
    isSummary: { type: Boolean, default: false }
  },

  render(createElement, { props }) {
    let cellContent;
    let cellData = {
      class: ['c-data-table__cell-data']
    };

    if (props.column.dataTemplate && !props.isSummary) {
      cellContent = props.column.dataTemplate(props.rowData, createElement);
    } else {
      const dataToShow = applyAutoFormatting(
        props.column.dataType,
        _.get(props.rowData, props.column.dataKey, '')
      );
      cellData.domProps = {
        innerHTML: dataToShow
      };
    }

    const labelData = {
      class: [
        'c-data-table__cell-mobile-label',
        'u-hidden-md',
        'u-hidden-lg',
        'u-text--bold',
        'u-mb1'
      ],
      domProps: {
        innerHTML: props.column.label
      }
    };

    return [
      createElement('span', labelData),
      createElement('span', cellData, cellContent)
    ];
  }
};
</script>
