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);
};

// 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}`);
  }
};

