const commonStatistic = require("../index.js");
const fs = require("fs");
const scheduler = require('@neuro-city/scheduler');

/** Выводит сообщение на страницу */
const showMessage = (type, ...args) => {
  args = ["[statistic]", ...args];
  let message = "";
  if (Array.isArray(args))
    args.forEach((arg) => {
      if (typeof arg === "object") {
        message += JSON.stringify(arg, null, "\t");
      } else {
        message += arg;
      }
      message += " ";
    });

  switch (type) {
    case "info":
      console.log(message);
      break;
    case "warn":
      console.warn(message);
      break;
    case "error":
      console.error(message);
      break;
    case "data":
      console.log(message);
      break;
    default:
      console.log(message);
      break;
  }

  //Если удалось найти HTML элементы для сообщений, дублируем сообщения в них
  const messageElem = document.getElementById("message");
  const messageConteiner = document.getElementById("message-conteiner");
  if (messageElem && messageConteiner) {
    messageConteiner.classList.add("show");
    messageElem.innerText += "\n\n" + message;
    messageElem.classList = type;
    messageConteiner.scrollTo(0, messageConteiner.scrollHeight);
  }
};

//Логгер
const log = {
  info: (...args) => showMessage("info", ...args),
  warn: (...args) => showMessage("warn", ...args),
  error: (...args) => showMessage("error", ...args),
  data: (...args) => showMessage("data", ...args),
};

//Подписываемся на события сообщений
commonStatistic.on("info", (info) => {
  log.info(info);
});
commonStatistic.on("error", (error) => {
  log.error(error);
});
commonStatistic.on("data", (data) => {
  log.data(data);
});

// scheduler.init({ remoteHref: 'https://test.neuro-ad.ru', deviceId: "5e185917a37f5e2e693701ac" })
// const { start, end } = scheduler.getTodayStartEnd()
const start = +(Date.now());
const end = start + (1000 * 60 * 60);
console.log(new Date(start), new Date(end))

//инициализирует статистическую систему, настраивает параметры и включает необходимые опции для сбора и отправки статистики.
fs.mkdirSync('./stats', { recursive: true }),
  commonStatistic.init({
    device: "5e185917a37f5e2e693701ac",
    serverAddress: 'https://test.neuro-ad.ru',
    collectStatistics: true,
    sendStatistics: true,
    logsPath: './stats',
    interval: 30,
    place: "5c110f69d1b4de28b0b5f29e",
    workInterval: 20,
    collectNetStat: true,
    startPeriod: start,
    endPeriod: end,
  });

let running = false;
let isSessionActive = false;
let isVideophoneActive = false;

/** запуск/остановка модуля статистики */
const handleStartStop = () => {
  if (running) {
    startButton.innerText = "Start";
    commonStatistic.stop();
    running = false;
  } else {
    startButton.innerText = "Stop";
    commonStatistic.start();
    running = true;
  }
};

/** запуск/остановка сбора пользовательской статистики */
const handleSession = () => {
  if (isSessionActive) {
    startSessionButton.innerText = "Start user session";
    isSessionActive = false;
    commonStatistic.endSession();
  } else {
    startSessionButton.innerText = "Stop user session";
    isSessionActive = true;
    commonStatistic.startSession({
      idleInterval: 0,
      startTheme: "bright",
      startLang: "ru",
    });
  }
};

/** записывает инфо о запросе на построение пути */
const handlePathAdd = () => {
  commonStatistic.addPathQuery();
};

/** записывает инфо о начале/окончании нового звонка по видеофону */
const handleVideophone = () => {
  if (isVideophoneActive) {
    videophoneButton.innerText = "Start call";
    isVideophoneActive = false;
    commonStatistic.endVideophone();
  } else {
    videophoneButton.innerText = "End call";
    isVideophoneActive = true;
    commonStatistic.startVideophone();
  }
};

/** записывает инфо о новой теме оформления */
const handleThemeChange = (themeName) => {
  commonStatistic.changeTheme(themeName);
};

/** записывает инфо о новом языке */
const handleLangChange = (langName) => {
  commonStatistic.changeLang(langName);
};

/** записывает инфо о клике на элемент меню */
const handleMenuClick = () => {
  commonStatistic.addMenuClick(menuSelect.value);
};

/** записывает инфо о действии с категориями */
const handleCategoryAction = (action) => {
  commonStatistic.addCategoryAction(categorySelect.value, action);
};

/** записывает инфо о действии с событиями */
const handleEventAction = (action) => {
  commonStatistic.addEventAction(eventSelect.value, action);
};

/** записывает инфо о действии с приоритетными объектами */
const handleObjectAction = (action) => {
  const [obj, type] = objectSelect.value.split("_");
  commonStatistic.addObjectAction(obj, action, type);
};

/** записывает инфо о передаче инфо\звонка на телефон пользователя */
const handleTakemobile = (storeType) => {
  commonStatistic.addTakemobile(takemobeleInput.value, storeType);
};

/** записывает инфо о старте проигрывания рекламного ролика (("session"|"idle"), тип проигывания, в пользовательской сессии или в режиме простоя) */
const handleStartAd = () => {
  if (isSessionActive) {
    commonStatistic.handleNeuroAdStart(adNameInput.value, "session")
  } else {
    commonStatistic.handleNeuroAdStart(adNameInput.value, "idle")
  }
}

/** записывает инфо о клике по рекламному ролику */
const handleClickAd = (type) => {
  commonStatistic.handleNeuroAdClick(adNameInput.value, type)
}

/** записывает инфо о том, что клиент забрал рекламную информацию на телефон */
const handleAdTakemobile = () => {
  commonStatistic.handleNeuroAdTakemobile(adNameInput.value, adClientInput.value)
}

/** записывает информацию о поисковом запросе и его результате */
const handleSearchAction = () => {
  commonStatistic.handleSearchQuery(searchQueryInput.value, searchKeywordInput.value.split(", "), foundIdInput.value)
}

const handleSms = () => {
  commonStatistic.handleSms({
    phoneNumber: smsPhone.value,
    status: smsStatus.value,
    error: smsError.value
  })
}

const handleEmail = () => {
  commonStatistic.handleMail({
    email: email.value,
    status: emailStatus.value,
    error: emailError.value
  })
}

const handleFlightRegistration = () => {
  commonStatistic.handleFlightRegistration({
    ticketNumber: ticketNumberInput.value,
    flightNumber: flightNumberInput.value,
    status: flightReqStatus.value,
    error: flightReqError.value
  })
}

const startButton = document.getElementById("start-btn");
const startSessionButton = document.getElementById("start-session-btn");
const pathButton = document.getElementById("path-btn");
const videophoneButton = document.getElementById("videophone-btn");

const brightThemeButton = document.getElementById("bright-theme-btn");
const darkThemeButton = document.getElementById("dark-theme-btn");

const russianButton = document.getElementById("ru-lang-btn");
const englishButton = document.getElementById("en-lang-btn");

const menuSelect = document.getElementById("menu-select");
const menuButton = document.getElementById("menu-btn");

const categorySelect = document.getElementById("category-select");
const categoryClickButton = document.getElementById("category-click-btn");
const categoryKeyboardButton = document.getElementById("category-keyboard-btn");
const categoryVoiceButton = document.getElementById("category-voice-btn");

const eventSelect = document.getElementById("event-select");
const eventClickButton = document.getElementById("event-click-btn");
const eventKeyboardButton = document.getElementById("event-keyboard-btn");
const eventVoiceButton = document.getElementById("event-voice-btn");

const objectSelect = document.getElementById("object-select");
const objectClickButton = document.getElementById("object-click-btn");
const objectVoiceButton = document.getElementById("object-voice-btn");
const objectKeyboardButton = document.getElementById("object-keyboard-btn");

const takemobeleInput = document.getElementById("takemobile-number");
const takemobeleGoogleButton = document.getElementById("google-play-btn");
const takemobeleAppleButton = document.getElementById("app-store-btn");
const adClientInput = document.getElementById('neuro-ad-client-input');
const takemobileAdButton = document.getElementById('takemobile-ad-btn');

const adNameInput = document.getElementById("neuro-ad-name");
const playAdButton = document.getElementById("play-ad-btn");
const clickAdButton = document.getElementById("click-ad-btn");
const tryTakemobileAdButton = document.getElementById("click-takemobile-ad");

const flightNumberInput = document.getElementById("flight-number");
const ticketNumberInput = document.getElementById("ticket-number");
const flightReqStatus = document.querySelector("#flight-registration #status");
const flightReqError = document.querySelector("#flight-registration #error");
const flightRegistrationButton = document.getElementById("flight-registration-btn");

const email = document.getElementById("email");
const emailStatus = document.querySelector("#mails #status");
const emailError = document.querySelector("#mails #error");
const emailButton = document.getElementById("mail-btn");

const smsPhone = document.getElementById("phone");
const smsStatus = document.querySelector("#smses #status");
const smsError = document.querySelector("#smses #error");
const smsButton = document.getElementById("sms-btn");

const searchQueryInput = document.getElementById("search-query");
const searchKeywordInput = document.getElementById("keywords");
const foundIdInput = document.getElementById("found");
const searchButton = document.getElementById("search-btn");

startButton.addEventListener("click", handleStartStop);
startSessionButton.addEventListener("click", handleSession);
pathButton.addEventListener("click", handlePathAdd);
videophoneButton.addEventListener("click", handleVideophone);

brightThemeButton.addEventListener("click", () => handleThemeChange("bright"));
darkThemeButton.addEventListener("click", () => handleThemeChange("dark"));

russianButton.addEventListener("click", () => handleLangChange("ru"));
englishButton.addEventListener("click", () => handleLangChange("en"));

menuButton.addEventListener("click", handleMenuClick);

categoryClickButton.addEventListener("click", () => handleCategoryAction("clickCount"));
categoryKeyboardButton.addEventListener("click", () => handleCategoryAction("keyboardCount"));
categoryVoiceButton.addEventListener("click", () => handleCategoryAction("voiceCount"));

eventClickButton.addEventListener("click", () => handleEventAction("clickCount"));
eventKeyboardButton.addEventListener("click", () => handleEventAction("keyboardCount"));
eventVoiceButton.addEventListener("click", () => handleEventAction("voiceCount"));

objectClickButton.addEventListener("click", () => handleObjectAction("clickCount"));
objectVoiceButton.addEventListener("click", () => handleObjectAction("voiceCount"));
objectKeyboardButton.addEventListener("click", () => handleObjectAction("keyboardCount"));

takemobeleAppleButton.addEventListener("click", () => handleTakemobile("appStore"));
takemobeleGoogleButton.addEventListener("click", () => handleTakemobile("googlePlay"));
playAdButton.addEventListener('click', handleStartAd);
clickAdButton.addEventListener('click', handleClickAd);
tryTakemobileAdButton.addEventListener('click', () => handleClickAd('takemobile'));
takemobileAdButton.addEventListener('click', handleAdTakemobile)

flightRegistrationButton.addEventListener('click', handleFlightRegistration)

searchButton.addEventListener("click", handleSearchAction)

emailButton.addEventListener("click", handleEmail);

smsButton.addEventListener("click", handleSms)

