const {app} = require('electron').remote;
const log = require('electron-log');
const mime = require('mime-types');
const url = require('url');

const classes = Object.freeze({
    container: 'content-container',
    content: 'content-container__item',
    active: 'content-container__item_active',
    prevActive: 'content-container__item_active_prev',
    video: 'content-container__item_video',
    image: 'content-container__item_image'
});
let document = null;
let container = null;
const customEvents = Object.freeze({
    mute: new Event('neuroad_mute'),
    unmute: new Event('neuroad_unmute'),
});
let currentItemData = {};

const init = (docElem) => {
    try {
        if ( !docElem ) {
            return log.error('mod:content-elems-controller init()', 'don\'t send document elem');
        }

        document = docElem;

        container = document.body.querySelector('.'+ classes.container);

        if ( !container ) {
            const putTo = (document.body.querySelector('.neuroad') || document.body);
            const div = document.createElement('div');
            div.classList.add(classes.container);

            putTo.appendChild(div);

            container = putTo.querySelector('.'+ classes.container);
        }
    } catch (e) {
        log.error('mod:content-elems-controller init() broken', e);
    }
};

const get = (filePath) => {
    try {
        if ( !document ) {
            return log.error('mod:content-elems-controller get()', 'need init() module and send document element before use other methods');
        } else if ( !filePath ) {
            return log.error('mod:content-elems-controller get()', 'don\'t send file path');
        }

        const contents = container.querySelectorAll('.'+ classes.content);
        let resultElem = find(filePath, contents);

        if ( !resultElem ) {
            let elem;

            if ( mime.lookup(filePath).indexOf('video') === 0 ) {
                elem = document.createElement('video');
                elem.classList.add(classes.video);
            } else {
                elem = document.createElement('img');
                elem.classList.add(classes.image);
            }

            elem.classList.add(classes.content);
            elem.setAttribute('src', filePath);

            container.appendChild(elem);

            resultElem = container.querySelectorAll('.'+ classes.content)[contents.length];
        }

        return resultElem;
    } catch (e) {
        log.error('mod:content-elems-controller get() broken', e);
    }
};

const show = (filePath) => {
    try {
        if ( !document ) {
            return log.error('mod:content-elems-controller show()', 'need init() module and send document element before use other methods');
        } else if ( !filePath ) {
            return log.error('mod:content-elems-controller show()', 'don\'t send file path');
        }

        const elemForShow = find(filePath);

        if ( !elemForShow ) {
            return log.error('mod:content-elems-controller show()', 'don\'t find content for show');
        }

        const currentActive = container.querySelector('.'+ classes.active);
        const prevActive = container.querySelector('.'+ classes.prevActive);

        elemForShow.classList.add(classes.active);

        if ( elemForShow === currentActive ) {
            return;
        }

        if ( currentActive ) {
            currentActive.classList.add(classes.prevActive);
            currentActive.classList.remove(classes.active);

            if ( currentActive.tagName === 'VIDEO' ) {
                currentActive.muted = true;
            }
        }

        if ( prevActive ) {
            prevActive.classList.remove(classes.prevActive);
        }
    } catch (e) {
        log.error('mod:content-elems-controller show() broken', e);
    }
};

const setMute = (mute) => {
    try {
        if ( !document ) {
            return log.error('mod:content-elems-controller setMute()', 'need init() module and send document element before use other methods');
        }

        if ( mute === undefined ) {
            mute = true;
        }

        container.querySelectorAll('.'+ classes.video).forEach((elem) => elem.muted = mute);

        if ( mute ) {
            document.dispatchEvent(customEvents.mute);
        } else {
            document.dispatchEvent(customEvents.unmute);
        }

        log.info('mod:content-elems-controller: set mute', mute);
    } catch (e) {
        log.error('mod:content-elems-controller setMute() broken', e);
    }
};

const find = (filePath, contents) => {
    try {
        let result = null;

        if ( !contents ) {
            contents = container.querySelectorAll('.'+ classes.content);
        }

        for ( let i = 0; i < contents.length; i++ ) {
            if ( contents[i].getAttribute('src') === filePath ) {
                result = contents[i];

                break;
            }
        }

        return result;
    } catch (e) {
        log.error('mod:content-elems-controller find() broken', e);
    }
};

const getLinkForPlayingContent = () => {
    try {
        const appPath = app.getPath('userData');

        if ( currentItemData.filePath.indexOf(appPath) !== 0 || !currentItemData.content_take_away ) {
            log.info('mod:content-elems-controller getLinkForPlayingContent()', 'current file can\'t take');

            return false;
        }

        let linkUrl = currentItemData.filePath.substr(appPath.length);

        if ( linkUrl ) {
            linkUrl = new URL(linkUrl, 'https://neuro-ad.com').href;
        } else {
            linkUrl = false;
            log.info('mod:content-elems-controller getLinkForPlayingContent()', 'error on create link');
        }

        return linkUrl;
    } catch (e) {
        log.error('mod:content-elems-controller getLinkForPlayingContent() broken', e);
    }
};

const saveCurrentContentData = (contentData) => {
    try {
        if ( typeof contentData === 'object' && contentData.filePath ) {
            currentItemData = contentData;
        } else {
            log.warn('mod:content-elems-controller saveCurrentContentData()', 'contentData is not object or bad');
        }
    } catch (e) {
        log.error('mod:content-elems-controller saveCurrentContentData() broken', e);
    }
};

module.exports = {
    init: init,
    get: get,
    show: show,
    setMute: setMute,
    getLinkForPlayingContent: getLinkForPlayingContent,
    saveCurrentContentData: saveCurrentContentData
};
