const { 
    initExample,
    createAndAddAudioEl,
    createAndAddVideoEl,
    createAndAddPhotoEl
} = require("./utils/exampleUtils.js");
const { 
    handleTextFeedback,
    handleFullName,
    handleMobileNumber,
    handleEmail,
    getAudioHandlers,
    getVideoHandlers,
    makePhoto,
    feedbackEmitter,
    getMediaContent,
    initFeedbackModule,
    submitData,
    handleGrade,
    clearRequestObject,
    getRequestObject
} = require("../dist/index.js");

//----------------------добавление прослушивания событий----------------------------
feedbackEmitter.on('error', (error) => {
    //логика обработки ошибки
    console.error('[feedback]', error);
})

feedbackEmitter.on('event', (text) => {
    //логика обработки события
    console.log('[feedback]', text);

    switch(text) {
        case('photo-added'):
            const { photo } = getMediaContent();
            console.log('[feedback]', photo);
            createAndAddPhotoEl(photo, photoFeedbackContainer);
            break;
        case('audio-added'):
            const { audio } = getMediaContent();
            console.log('[feedback]', audio);
            createAndAddAudioEl(audio, audioFeedbackContainer);
            break;
        case('video-added'):
            let { video } = getMediaContent();
            console.log('[feedback]', video);
            createAndAddVideoEl(video, videoFeedbackContainer);
            break;
        case('video-rotated'):
            console.log('[feedback]', getMediaContent().video);
            createAndAddVideoEl(getMediaContent().video, videoFeedbackContainer);
            break;
        default:
            console.warn('[feedback]', `Необрабатываемое событие: ${text}`);
            break;
    }
})

feedbackEmitter.on('inited', (data) => {
    console.log('[feedback]', data);
})

feedbackEmitter.on('data', (data) => {
    //логика работы с данными
    console.log('[feedback]', data);
})

feedbackEmitter.on('sended', (data) => {
    console.log('[feedback]', data);
})

const serverUrl = 'https://back-space.neuro-city.ru/';

initExample();
initFeedbackModule(
    serverUrl, //адрес сервера отзывов
    "90", //угол поворота камеры
    "feedback@neuro-city.ru", //логин пользователя для отправки отзывов
    "vdnhvdnh", //пароль пользователя для отправки отзывов
    "6380c8f9ddd3421bd76714c6", //ID платформы с которой отпраляется отзыв (необязателен)
    "65fda214f253f13a4f7bf805" //ID устройства с которого отпраляется отзыв (необязателен)
);

//textareas
const feedbackContentTextArea = document.getElementById("text-content-text-area");
const fullNameTextArea = document.getElementById("full-name-text-area");
const mobileNumberTextArea = document.getElementById("mobile-number-text-area");
const emailTextArea = document.getElementById("email-text-area");

//audio
const audioFeedbackContainer = document.getElementById("feedback-form__audio-content-container");
const audioStartRecordingButton = document.getElementById("audio-start");
const audioStopRecordingButton = document.getElementById("audio-stop");
const audioStopStreamButton = document.getElementById("audioStream-stop");

//video
const videoFeedbackContainer = document.getElementById("feedback-form__video-content-container");
const videoStartRecordingButton = document.getElementById("video-start"); 
const videoStopRecordingButton = document.getElementById("video-stop");
const videoStopStreamButton = document.getElementById("videoStream-stop");

//photo
const photoFeedbackContainer = document.getElementById("feedback-form__photo-container");
const makePhotoButton = document.getElementById("photo-make");

//radio buttons (grade)
const rangeInput = document.getElementById("feedback-form__range");
const valueCounter = document.getElementById("feedback-form__value");
const selectPopUp = document.getElementById("feedback-form__select");
const gradeNameTextArea = document.getElementById("grade-name-text-area");
const gradeTypeTextArea = document.getElementById("grade-type-text-area");
// const radioButtonsForm = document.getElementById("feedback-form__grade-radio-buttons");

//кнопки управления модулем
const submitAllButton = document.getElementById("submit-all-button");
submitAllButton.innerText = `Submit all data (${serverUrl})`
const clearReqObjButton = document.getElementById("clear-request-object");
const getReqObjButton = document.getElementById("get-request-object");

let startAudio = null;
let stopAudio = null;
let startVideo = null;
let stopVideo = null;
let stopVideoStream = null;
let stopAudioStream = null;
let maxGradeValue = 5;
let currentGrade = 5;

//---------------------------audio-----------------------------------------------
navigator.mediaDevices.getUserMedia({ audio: true})
.then((stream) => {
    [startAudio, stopAudio, stopAudioStream] = getAudioHandlers(stream);
})

audioStartRecordingButton.addEventListener('click', () => startAudio());
audioStopRecordingButton.addEventListener('click', () => stopAudio());
audioStopStreamButton.addEventListener('click', () => stopAudioStream());
//--------------------------------------------------------------------------------
//---------------------------video------------------------------------------------
navigator.mediaDevices.getUserMedia({ audio: true, video: true })
.then((stream) => {
    [startVideo, stopVideo, stopVideoStream] = getVideoHandlers(stream);
})

videoStartRecordingButton.addEventListener('click', () => startVideo());
videoStopRecordingButton.addEventListener('click', () => stopVideo());
videoStopStreamButton.addEventListener('click', () => stopVideoStream());
//--------------------------------------------------------------------------------
//---------------------------photo------------------------------------------------
makePhotoButton.addEventListener('click', () => makePhoto());
//--------------------------------------------------------------------------------
feedbackContentTextArea.addEventListener('blur', () => {
    handleTextFeedback(feedbackContentTextArea.value);
    if (feedbackContentTextArea.value) {
        const feedbackButtons = document.querySelectorAll('.feedback-type-button');
        feedbackButtons.forEach(button => {
            if (button.innerHTML === 'Text') {
                button.classList.add('active');
            } else {
                button.classList.remove('active');
            };
        });
    }
});

fullNameTextArea.addEventListener('blur', () => {
    handleFullName(fullNameTextArea.value);
})

mobileNumberTextArea.addEventListener('blur', () => {
    handleMobileNumber(mobileNumberTextArea.value);
})

emailTextArea.addEventListener('blur', () => {
    handleEmail(emailTextArea.value);
})

submitAllButton.addEventListener('click', () => submitData());
clearReqObjButton.addEventListener('click', () => clearRequestObject());
getReqObjButton.addEventListener('click', () => {
    const data = getRequestObject();
    console.log('[feedback]', data);
});

/* ---------------------------------------------------------------------------------
   ----------------------------Grade------------------------------------------------ */
rangeInput.addEventListener('change', (event) => {
    valueCounter.innerHTML = event.target.value;
    currentGrade = event.target.value;
    handleGrade(currentGrade, maxGradeValue, gradeNameTextArea.value || null, gradeTypeTextArea.value || null);
})

selectPopUp.addEventListener('change', (event) => {
    maxGradeValue = Number(event.target.value);
    rangeInput.max = maxGradeValue;
    if (currentGrade > maxGradeValue) {
        currentGrade = maxGradeValue;
        valueCounter.innerHTML = currentGrade;
    }
    handleGrade(currentGrade, maxGradeValue, gradeNameTextArea.value || null, gradeTypeTextArea.value || null);
})