'use strict';
exports.__esModule = true;
var cheerio = require("cheerio");
var episode_1 = require("./episode");
// import fs = require('fs');
var fs = require("fs-extra");
var my_request = require("./my_request");
var path = require("path");
var url = require("url");
var log = require("./log");
var persistent = '.crpersistent';
/**
 * Check if a file exist..
 */
function fileExist(path) {
    try {
        fs.statSync(path);
        return true;
    }
    catch (e) {
        return false;
    }
}
/**
 * Streams the series to disk.
 */
function default_1(config, address, done) {
    var persistentPath = path.join(config.output || process.cwd(), persistent);
    /* Make a backup of the persistent file in case of */
    if (fileExist(persistentPath)) {
        fs.copySync(persistentPath, persistentPath + '.backup');
    }
    fs.readFile(persistentPath, 'utf8', function (err, contents) {
        var cache = config.cache ? {} : JSON.parse(contents || '{}');
        page(config, address, function (errP, page) {
            if (errP) {
                return done(errP);
            }
            var i = 0;
            (function next() {
                if (i >= page.episodes.length)
                    return done(null);
                download(cache, config, address, page.episodes[i], function (errD, ignored) {
                    if (errD) {
                        if (page.episodes[i].retry <= 0) {
                            log.dispEpisode(config.filename, 'Error...', true);
                            console.error(err);
                            log.error('Cannot fetch episode "s' + page.episodes[i].volume + 'e' + page.episodes[i].episode +
                                '", please rerun later');
                        }
                        else {
                            log.dispEpisode(config.filename, 'Error...', true);
                            if (config.verbose) {
                                console.error(errD);
                            }
                            log.warn('Retrying to fetch episode "s' + page.episodes[i].volume + 'e' + page.episodes[i].episode +
                                '" - Retry ' + page.episodes[i].retry + ' / ' + config.retry);
                            page.episodes[i].retry -= 1;
                        }
                        next();
                    }
                    else {
                        if ((ignored === false) || (ignored === undefined)) {
                            var newCache = JSON.stringify(cache, null, '  ');
                            fs.writeFile(persistentPath, newCache, function (errW) {
                                if (errW) {
                                    return done(errW);
                                }
                                i += 1;
                                next();
                            });
                        }
                        else {
                            i += 1;
                            next();
                        }
                    }
                });
            })();
        });
    });
}
exports["default"] = default_1;
/**
 * Downloads the episode.
 */
function download(cache, config, baseAddress, item, done) {
    if (!filter(config, item)) {
        return done(null, false);
    }
    var address = url.resolve(baseAddress, item.address);
    if (cache[address]) {
        return done(null, false);
    }
    episode_1["default"](config, address, function (err, ignored) {
        if (err) {
            return done(err, false);
        }
        cache[address] = Date.now();
        done(null, ignored);
    });
}
/**
 * Filters the item based on the configuration.
 */
function filter(config, item) {
    // Filter on chapter.
    var episodeFilter = config.episode;
    // Filter on volume.
    var volumeFilter = config.volume;
    var currentEpisode = parseInt(item.episode, 10);
    var currentVolume = item.volume;
    if (((episodeFilter > 0) && (currentEpisode <= episodeFilter)) ||
        ((episodeFilter < 0) && (currentEpisode >= -episodeFilter)) ||
        ((volumeFilter > 0) && (currentVolume <= volumeFilter)) ||
        ((volumeFilter < 0) && (currentVolume >= -volumeFilter))) {
        return false;
    }
    return true;
}
/**
 * Requests the page and scrapes the episodes and series.
 */
function page(config, address, done) {
    if (address[0] === '@') {
        log.info('Trying to fetch from ' + address.substr(1));
        var episodes = [];
        episodes.push({
            address: address.substr(1),
            episode: '',
            volume: 0,
            retry: config.retry
        });
        done(null, { episodes: episodes.reverse(), series: '' });
    }
    else {
        var episodeCount_1 = 0;
        my_request.get(config, address, function (err, result) {
            if (err) {
                return done(err);
            }
            var $ = cheerio.load(result);
            var title = $('span[itemprop=name]').text();
            if (!title) {
                return done(new Error('Invalid page.(' + address + ')'));
            }
            log.info('Checking availability for ' + title);
            var episodes = [];
            $('.episode').each(function (i, el) {
                if ($(el).children('img[src*=coming_soon]').length) {
                    return;
                }
                var volume = /([0-9]+)\s*$/.exec($(el).closest('ul').prev('a').text());
                var regexp = /Episode\s+((PV )?[S0-9][\-P0-9.]*[a-fA-F]?)\s*$/i;
                var episode = regexp.exec($(el).children('.series-title').text());
                var url = $(el).attr('href');
                if ((!url) || (!episode)) {
                    return;
                }
                episodeCount_1 += 1;
                episodes.push({
                    address: url,
                    episode: episode[1],
                    volume: volume ? parseInt(volume[0], 10) : 1,
                    retry: config.retry
                });
            });
            if (episodeCount_1 === 0) {
                log.warn('No episodes found for ' + title + '. Could it be a movie?');
            }
            done(null, { episodes: episodes.reverse(), series: title });
        });
    }
}
//# sourceMappingURL=series.js.map