let indent = 0;

serialize = (obj, i) => {
  if (Array.isArray(obj)) {
    return get_arr(obj, i);
  } else if (typeof obj === "object") {
    return get_obj(obj, i);
  } else if (typeof obj == "string") {
    return get_str(obj);
  } else {
    return obj;
  }
};

get_str = (str) => {
  const php_regex = /<\?php (.*)/s;
  let match = str.match(php_regex);
  if (match && Array.isArray(match) && match.length > 1) {
    return match[1];
  }
  return '"' + str.replace('"', '""') + '"';
};

get_obj = (obj, i) => {
  let inner = Object.entries(obj).reduce((res, [prop, value]) => {
    return res + line(get_str(prop) + " => " + serialize(value, i + 1), i + 1);
  }, "");
  return arr_line(inner, i);
};

get_arr = (obj, i) => {
  let inner = obj.reduce((res, value) => {
    return res + line(serialize(value, i + 1), i + 1);
  }, "");
  return arr_line(inner, i);
};

line = (str, i) => {
  return eol(i) + str + ",";
};

arr_line = (str, i) => {
  if (str) {
    return "[" + str + eol(i) + "]";
  } else {
    return "[]";
  }
};

eol = (indent) => {
  return (
    "\n" +
    Array(4 * indent)
      .fill(" ")
      .join("")
  );
};

php_serialize = (obj, variableName) => {
  return 'define("' + variableName + '", ' + serialize(obj, 0) + ");";
};

module.exports = {
  serialize: php_serialize,
};
