import _ from 'lodash';
import { datasourceApi } from '../services/datasource';


export const getData = async (coordinate, { pst, psz, params = {}, filters = [], sortBys = [], sortTypes = [] }) => {
  const options = { pst, psz, params, filters, sortBys, sortTypes };
  const api = datasourceApi(coordinate);
  const meta = await api.meta();
  const dsb = await api.query(options);
  return getArrayData(dsb, meta);
};
export const getMeta = async (coordinate) => {
  const api = datasourceApi(coordinate);
  const meta = await api.meta();
  return makeColumns(meta);
};
const parseMetas = (metas) => {
  const ret = {};
  if (!metas) {
    return ret;
  }
  _.forEach(metas, (value, key) => {
    let finalValue;
    try {
      finalValue = JSON.parse(value);
    } catch (err) {
      finalValue = value;
    }
    _.set(ret, key, finalValue);
  });
  return _.pickBy(ret, _.negate(_.isUndefined));
};
const makeColumns = (meta) => {
  return (meta.properties || [])
    .filter(property => !property.skip)
    .map((property) => {
      const props = parseMetas(property.metas);
      if (!props.title && props.label) {
        props.title = props.label;
      }
      if (props.order === undefined) {
        props.order = 0;
      }
      if ((props.fixed === true || props.fixed === 'left' || props.fixed === 'right') && props.width === undefined) {
        props.width = 150;
      }
      return _.pickBy({
        ...props,
        key: property.name,
        required: property.required,
      }, _.negate(_.isUndefined));
    })
    .filter(c => c.visible !== false);
};


// const tmp = async(ddd) => {
// await
// }

// function abc() {
//
//   for (cont a of b) {
//     await a()
//   }
//   getData().then((r) => {
//
//   }).catch(err => {
//
//   })
// }

const getArrayData = ({ dataType, arrayData, singularData }, meta) => {
  if (dataType === 'TABLE') {
    const data = (arrayData || []).map(() => ({}));
    (meta.properties || [])
      .filter(property => !property.skip)
      .forEach((property, i) => {
        data.forEach((row, j) => {
          row[property.name] = arrayData[j][i]; // eslint-disable-line no-param-reassign
        });
      });
    return data;
  } else if (dataType === 'PROPERTIES') {
    const data = [];
    (meta.properties || [])
      .filter(property => !property.skip)
      .forEach((property) => {
        data.push((singularData || {})[property.name]);
      });
    return [_.toPlainObject(data)];
  } else {
    throw new Error(`Unsupported data type: ${dataType}`);
  }
};

