export const dayOfWeeksNames = [
  "понедельник",
  "вторник",
  "cреда",
  "четверг",
  "пятница",
  "суббота",
  "воскресенье",
];
export const monthNames = [
  "января",
  "февраля",
  "марта",
  "апреля",
  "мая",
  "июня",
  "июля",
  "августа",
  "сентября",
  "октября",
  "ноября",
  "декабря",
];

export const dateTagsList = {
  today: "сегодня",
  tomorrow: "завтра",
  yesterday: "вчера",
  afterTomorrow: "послезавтра",
};

/**
 * @param {Date} date
 */
export function getDateTags(date) {
  const x = new Date();
  x.setHours(0, 0, 0, 0);
  const t = new Date(date);
  t.setHours(0, 0, 0, 0);
  const diff = (t - x) / 86400000; // days difference
  return diff === 0
    ? dateTagsList["today"]
    : diff === -1
      ? dateTagsList["yesterday"]
      : diff === 1
        ? dateTagsList["tomorrow"]
        : diff === 2
          ? dateTagsList["afterTomorrow"]
          : "";
}
/**
 * Converts day of the week with 0 - sunday, to 0 - monday
 * @param {number} usDay
 */
export function usToRussianDay(usDay) {
  return (usDay + 6) % 7;
}
/**
 * @param {Date} date
 */
export function formatDate(date) {
  return `${
    dayOfWeeksNames[usToRussianDay(date.getDay())]
  }, ${date.getDate()} ${monthNames[date.getMonth()]}${
    date.getFullYear() != new Date().getFullYear()
      ? " " + date.getFullYear()
      : ""
  }`;
}
/**
 * @param {Date} date
 */
export function apiFormatDate(date) {
  return (
    ("0" + date.getDate()).slice(-2) +
    "-" +
    ("0" + (date.getMonth() + 1)).slice(-2) +
    "-" +
    String(date.getFullYear()).slice(-2)
  );
}
/**
 * @param {string} s
 */
export const parseApiDate = (s) => {
  const [d, m, y] = s.split("-").map(Number);
  const yy = 2000 + y;
  return new Date(yy, m - 1, d);
};

export const apiToEditorVocabluary = {
  // api: editor
  num: "position",
  cabinet: "room",
  subject: "subject",
  "t-begin": "time1",
  "t-end": "time2",
};

/**
 * Converts api schedule data to editor format
 * @param {{num: string|number; cabinet: string|number, subject: string, "t-begin": string, "t-end": string}[]} arr
 * @returns {{position: string|number; room: string|number; subject: string, time1: string, time2: string}[]}
 */
export function convertApiToEditor(arr) {
  let uuid = Math.floor(Math.random() * 10000);
  return arr.map((item) => {
    const converted = {};
    for (const [apiKey, editorKey] of Object.entries(apiToEditorVocabluary)) {
      if (Object.prototype.hasOwnProperty.call(item, apiKey)) {
        converted[editorKey] = item[apiKey];
      }
    }
    converted.id = uuid;
    uuid += Math.floor(Math.random() * 10000);
    return converted;
  });
}

/**
 * Converts editor schedule data to api format
 * @param {{position: string|number; room: string|number; subject: string, time1: string, time2: string}[]} arr
 * @returns {{num: string|number; cabinet: string|number, subject: string, "t-begin": string, "t-end": string}[]}
 */
export function convertEditorToApi(arr) {
  const editorToApi = Object.fromEntries(
    Object.entries(apiToEditorVocabluary).map(([apiKey, editorKey]) => [
      editorKey,
      apiKey,
    ]),
  );

  return arr.reduce((acc, item) => {
    const converted = {};
    for (const [editorKey, apiKey] of Object.entries(editorToApi)) {
      if (!Object.prototype.hasOwnProperty.call(item, editorKey)) continue;

      const value = item[editorKey];
      if (
        (editorKey === "time1" || editorKey === "time2") &&
        (value === "" || value == null)
      ) {
        // фиг вам
        continue;
      }
      if (editorKey === "subject" && value === "") {
        // ваще наху
        return acc;
      }

      converted[apiKey] = value;
    }
    acc.push(converted);
    return acc;
  }, []);
}
/**
 * Checks if time string (HH:MM) before now
 * @param {string} timeStr
 */
export function isTimeBeforeNow(timeStr) {
  const [h, m] = timeStr.split(":").map(Number);
  if (!Number.isFinite(h) || !Number.isFinite(m)) return false;
  const now = new Date();
  const t = new Date(
    now.getFullYear(),
    now.getMonth(),
    now.getDate(),
    h,
    m,
    0,
    0,
  );
  return t.getTime() < now.getTime();
}
export const premsMeanings = {
  "-1": "неограниченый",
  // 0: "reserved"
  1: "обычный",
  2: "управляющий",
};

export const AvailableSymbols = (() => {
  const a = "abcdefghijklmnopqrstuvwxyz"; // alphabet
  const A = a.toUpperCase(); // ALPHABET
  const n = "1234567890"; // numbers
  const s = "_-"; // specials
  return (a + n + A + s).split("");
})();

export const AvailableAdminSymbols = [
  ...AvailableSymbols,
  ..."$()*^%@!+=.".split(""),
];
