const log = require('electron-log');
const mime = require('mime-types');
const fs = require('fs');

module.exports = (pathToVideo) => new Promise((resolve) => {
    try {
        let duration = 0;

        if ( !pathToVideo || !fs.existsSync(pathToVideo) ) {
            log.error('no path to video or video not exists!');

            resolve(duration);
        }

        const videoElem = document.createElement('video');
        videoElem.muted = true;
        videoElem.src = pathToVideo;

        const play = videoElem.play();

        play
            .then(() => {
                let index = 0;
                const getDuration = () => {
                    duration = videoElem.duration || 0;

                    if ( duration > 0 ) {
                        log.info(`getVideoDuration() video "${pathToVideo}" duration: `, duration);

                        videoElem.remove();
                        resolve(duration);
                    } else {
                        index++;

                        if ( index > 10 ) {
                            log.error('can\'t get video duration!');

                            videoElem.remove();
                            resolve(duration);
                        } else {
                            setTimeout(() => getDuration(), 1000);
                        }
                    }
                };

                getDuration();
            })
            .catch((error) => {
                log.error('getVideoDuration() can\'t play() video\n', error);

                videoElem.remove();

                resolve(duration);
            });
    } catch (err) {
        log.error('page:neuro-ad mod:get-video-duration', err);
    }
});
