import { NotImplementedError } from "../extensions/index.js";

/**
 * Given an array of domains, return the object with the appearances of the DNS.
 *
 * @param {Array} domains
 * @return {Object}
 *
 * @example
 * domains = [
 *  'code.yandex.ru',
 *  'music.yandex.ru',
 *  'yandex.ru'
 * ]
 *
 * The result should be the following:
 * {
 *   '.ru': 3,
 *   '.ru.yandex': 3,
 *   '.ru.yandex.code': 1,
 *   '.ru.yandex.music': 1,
 * }
 *
 */
export default function getDNSStats(domains) {
  let result = {};

  for (let i = 0; i < domains.length; i++) {
    let level1 = domains[i].match(/\.\w+$/);
    if (level1 != null) {
      if (!result[level1]) {
        result[level1] = 1;
      } else {
        result[level1]++;
      }
    }

    let level2 = domains[i].match(/(\.\w+)(\.\w+$)/);
    if (level2 != null) {
      level2 = level2[2] + level2[1];
      if (!result[level2]) {
        result[level2] = 1;
      } else {
        result[level2]++;
      }
    }

    let level3 = domains[i].match(/(^\w+)(\.\w+$)/);
    if (level3 != null) {
      level3 = level3[2] + "." + level3[1];
      if (!result[level3]) {
        result[level3] = 1;
      } else {
        result[level3]++;
      }
    }

    let level4 = domains[i].match(/(^\w+)(\.\w+)(\.\w+$)/);
    if (level4 != null) {
      level4 = level4[3] + level4[2] + "." + level4[1];
      if (!result[level4]) {
        result[level4] = 1;
      } else {
        result[level4]++;
      }
    }
  }

  return result;
}
