const log = require('electron-log');
const moment = require('moment');

const popup = require('../popup');
const createElems = require('./create-elems');

/* TODO:
* autoscroll
* more info about playlist items:
* - repeats info (all, for item? for day? current session for every items?)
* - volume/mute for items (set only for played before and current or only current)
* - global volume
* - content take away
* - key,
* - "info index"
* - "update data by"
* - add/update every second current item playing time
* date for last get data info and date for last success get data
*
* */

let currentPlayedItem = {};
let currentBlocksStartTime = [];
let currentContentStartTime = [];

const setEventsListeners = () => {
    try {
        document.addEventListener('info-popup.afterShow', () => newPlaylist());
    } catch (e) {
        log.error('Error: info-popup/playlist setEventsListeners()', e);
    }
};

setEventsListeners();

const newPlaylist = (blocksStartTime, contentStartTime) => {
    try {
        if ( popup?.isHiddenPopup() ) {
            return false;
        }

        if ( blocksStartTime && contentStartTime ) {
            currentBlocksStartTime = Array.from(blocksStartTime);
            currentContentStartTime = Array.from(contentStartTime);

            popup.elem.querySelector('.js-info-popup__playlist-created-at').innerHTML = moment().format('HH:mm:ss');
        }

        createElems.playlist(currentBlocksStartTime, currentContentStartTime, updatePlayedInfo);
    } catch (e) {
        log.error('Error: info-popup/playlist newPlaylist()', e);
    }
};

const updatePlayedInfo = (currentItem) => {
    try {
        if ( popup?.isHiddenPopup() ) {
            return false;
        }

        if ( currentItem ) {
            currentPlayedItem = Object.assign({}, currentItem);
        }

        const contentItems = popup.elem.querySelectorAll('[data-content-id]');

        for ( let i = 0; i < contentItems.length; i++ ) {
            const item = contentItems[i];
            const itemStartTime = parseInt(item.dataset.contentStartTime, 10);

            if ( itemStartTime < parseInt(currentPlayedItem.startTime, 10) ) {
                item.classList.remove('info-popup-playlist__content-item_current');
                item.classList.add('info-popup-playlist__content-item_played');
            } else {
                item.classList.add('info-popup-playlist__content-item_current');

                break;
            }
        }
    } catch (e) {
        log.error('Error: info-popup/playlist updatePlayedInfo()', e);
    }
};

module.exports = {
    newPlaylist,
    updatePlayedInfo,
};
