/**
 * CCDN 1.4.17
 */

$(function () {
    $('.parse-database-js').on('click', function () {
        if (!PARSE_DATABASE_CFG.domain_data) {
            alert('Failed to get domain with domain_data');
            return;
        }

        let that = $(this);
        const moviesUrl = PARSE_DATABASE_CFG.domain_data + '/data/movies.json';
        $.get(moviesUrl).done(response => {
            return response;
        }).then(response => {

            let type = that.data('franchise-type');

            let moviesHandler = new MoviesHandler(response);
            let data = moviesHandler.getAllByType(type);

            let url = $('#data-url-action').data('url-action');
            let progressbar = $('#progress-bar-' + type).find('.progress-bar');
            load(url, data.total, data.items, progressbar);
        })
    });
});


/**

 * @param data
 * @constructor
 */
function MoviesHandler(data) {
    this.date = data.results;
}

/**
 *
 * @param type
 * @return {{total: {integer}, items: {array}}}
 */
MoviesHandler.prototype.getAllByType = function (type) {

    let items = this.date.filter(function (item) {
        return item.type === type;
    });

    return {
        'total': items.length,
        'items': items,
    }
};

/**
 * @param url
 * @param total
 * @param $items
 * @param progressbar
 * @return {Promise<void>}
 */
async function load(url, total, $items, progressbar) {

    let countPars = parseInt($('#pars-count').val());

    for (let i = 0; i < total; i++) {
        if (yearFilter($items[i])) {
            drawProgressBar(total, i, progressbar);
            continue;
        }

        await sleep(50);
        try {
            let r = await fetch(url, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded',
                },
                body: 'genreFilter=' + JSON.stringify(Object.assign({}, $('#genres').val()))
                    + '&countryFilter=' + JSON.stringify(Object.assign({}, $('#country').val()))
                    + '&franchiseStatus=' + $('#franchiseStatus').val()
                    + '&item=' + encodeURIComponent(JSON.stringify($items[i]))
            });

            if (!isNaN(countPars) && r.ok) {
                if (countPars === 1) {
                    drawProgressBar(total, total - 1, progressbar);
                    break;
                }
                countPars--;
            }
            drawProgressBar(total, i, progressbar);
        } catch (error) {
            console.log('/*** Error ***/');
            console.log(error);
            break;
        }
    }
}

function drawProgressBar(total, current, progressbar) {
    const percent = ((current + 1) / total) * 100;
    let testProgress = Math.round(percent);
    progressbar.css('width', percent + '%').html(testProgress + '%');
}

const sleep = (milliseconds) => {
    return new Promise(resolve => {
        setTimeout(resolve, milliseconds)
    })
};


/**
 * @param item
 * @return {boolean}
 */
function yearFilter(item) {
    let yearsInputValue = document.getElementById('year').value;
    if (yearsInputValue.length === 0) {
        return false;
    }

    if (yearsInputValue.includes('-')) {
        let years = yearsInputValue.split('-')
            .map(function (value) {
                return parseInt(value);
            }).sort(function (a, b) {
                return a - b;
            });
        return !(item.year >= years[0] && item.year <= years[1]);
    } else {
        let years = yearsInputValue.split(',');
        return !years.includes(item.year.toString())
    }
}
