/* eslint-disable */
import style from './style.sjs';

const REGEXP = getRegExp('^-?\d+(\.\d+)?$');

function addUnit(value) {
  if (value == null) {
    return undefined;
  }
  return REGEXP.test('' + value) ? value + 'px' : value;
}

function isObj(x) {
  const type = typeof x;
  return x !== null && (type === 'object' || type === 'function');
}

function optionText(option, valueKey) {
  return isObj(option) && option[valueKey] != null ? option[valueKey] : option;
}

function rootStyle(data) {
  const res = style.style({
    height: addUnit(data.itemHeight * data.visibleItemCount)
  });
  return res;
}

function wrapperStyle(data) {
  const offset = addUnit(
    data.offset + (data.itemHeight * (data.visibleItemCount - 1)) / 2
  );

  const res = style.style({
    'transition-duration':  data.duration + 'ms',
    transform: 'translate3d(0px, ' + offset + 'px, 0)'
  });
  return res;
}

const PREFIX = 'adc-';

function join(name, mods) {
  name = PREFIX + name;
  mods = mods.map(function (mod) {
    return name + '--' + mod;
  });
  mods.unshift(name);
  return mods.join(' ');
}

function traversing(mods, conf) {
  if (!conf) {
    return;
  }

  if (typeof conf === 'string' || typeof conf === 'number') {
    mods.push(conf);
  } else if (style.isArray(conf)) {
    conf.forEach(function (item) {
      traversing(mods, item);
    });
  } else if (typeof conf === 'object') {
    style.keys(conf).forEach(function (key) {
      conf[key] && mods.push(key);
    });
  }
}

function bem(name, conf) {
  const mods = [];
  traversing(mods, conf);
  return join(name, mods);
}

export default {
  optionText: optionText,
  rootStyle: rootStyle,
  wrapperStyle: wrapperStyle,
  bem
};
