const log = require('electron-log');
const path = require('path');
const fs = require('fs');

const getRandomInt = require('../get-random-integer');

const classes = Object.freeze({
    container: 'neuroad-guide',
    containerShow: 'neuroad-guide_show',
    video: 'neuroad-guide__video',
    activeVideo: 'neuroad-guide__video_active'
});
let container = null;
let intervalId = null;

const getVideosFromDir = (dirPath) => {
    const videos = [];

    if (!fs.existsSync(dirPath)) {
        return videos;
    }

    const filenames = fs.readdirSync(dirPath);

    if (!filenames || filenames.length < 1) {
        return videos;
    }

    filenames.forEach(function(filename) {
        const { ext } = path.parse(filename);

        if ( ext === '.webm' || ext === '.mp4' ) {
            videos.push(filename);
        }
    });

    return videos;
};

const autoplay = () => {
    try {
        const videosRootPath = path.resolve(__dirname, '../../../../../videos/nad-guides');
        const videoNames = getVideosFromDir(videosRootPath);
        let remainingVideoNames = [];
        const delayPlayTime = 1000 * 15;

        if (!videoNames || videoNames.length < 1) {
            return;
        }

        intervalId = setInterval(() => {
            if ( remainingVideoNames.length < 1 ) {
                remainingVideoNames = Array.from(videoNames);
            }

            const newVideoName = remainingVideoNames.splice(getRandomInt(0, remainingVideoNames.length), 1);
            const newVideoPath = videosRootPath +'/'+ newVideoName;

            play(newVideoPath);
        }, delayPlayTime);
    } catch (e) {
        log.error('mod:page/guide:autoplay() broken', e);
    }
};

const play = (videoPath) => {
    try {
        if ( !_checkVideosContainer() ) {
            return false;
        }

        const videoElem = _getVideoElem(videoPath);

        container.classList.add(classes.containerShow);

        container.querySelectorAll(`.${classes.activeVideo}`)
            .forEach((elem) => elem.classList.remove(classes.activeVideo));

        if ( !videoElem ) {
            return log.error('mod:page/guide:play()', `don't get video element`);
        }

        videoElem.play().then(() => {
            videoElem.classList.add(classes.activeVideo);

            const mainGuideVideo = document.body.querySelector('#guide_video_cnt video');

            videoElem.volume = (mainGuideVideo ? mainGuideVideo.volume : 0);
        }).catch((e) => log.warn('mod:page/guide:play()', e));
    } catch (e) {
        log.error('mod:page/guide:play() broken', e);
    }
};

const _getVideoElem = (videoPath) => {
    try {
        if ( !videoPath ) {
            return log.error('mod:page/guide:_getVideoElem()', `don't send video path`);
        } else if ( !_checkVideosContainer() ) {
            return false;
        }

        let videoElem = container.querySelector(`.${classes.video}[src="${videoPath}"]`);

        if ( !videoElem ) {
            const newElem = document.createElement('video');
            newElem.classList.add(classes.video);
            newElem.setAttribute('src', videoPath);

            videoElem = container.appendChild(newElem);

            if ( !videoElem ) {
                return log.error('mod:page/guide:_getVideoElem()', `don't create new video elem`);
            }
        }

        return videoElem;
    } catch (e) {
        log.error('mod:page/guide:_getVideoElem() broken', e);
    }
};

const _checkVideosContainer = () => {
    try {
        if ( !container ) {
            container = document.body.querySelector('.'+classes.container);
        }

        if ( !container ) {
            return log.error('mod:page/guide:_checkVideosContainer()', `don't find gide container`);
        }

        return true;
    } catch (e) {
        log.error('mod:page/guide:_checkVideosContainer() broken', e);
    }
};

const destroy = () => {
    try {
        if ( intervalId ) {
            clearInterval(intervalId);
            intervalId = null;
        }

        if ( container ) {
            container.classList.remove(classes.containerShow);
            container.querySelectorAll('.'+ classes.video).forEach((elem) => elem.remove());
            container = null;
        }
    } catch (e) {
        log.error('mod:page/guide:destroy() broken', e);
    }
};

module.exports = {
    autoplay: autoplay,
    destroy: destroy
};
