"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const funi_1 = __importDefault(require("../../../funi"));
const module_args_1 = require("../../../modules/module.args");
const module_langsData_1 = require("../../../modules/module.langsData");
const base_1 = __importDefault(require("./base"));
const log_1 = require("../../../modules/log");
const yargs = __importStar(require("../../../modules/module.app-args"));
class FunimationHandler extends base_1.default {
    constructor(ws) {
        super(ws);
        this.name = 'funi';
        this.funi = new funi_1.default();
        this.initState();
    }
    listEpisodes(id) {
        return __awaiter(this, void 0, void 0, function* () {
            const parse = parseInt(id);
            if (isNaN(parse) || parse <= 0)
                return { isOk: false, reason: new Error('The ID is invalid') };
            const request = yield this.funi.listShowItems(parse);
            if (!request.isOk)
                return request;
            return { isOk: true, value: request.value.map(item => {
                    var _a, _b, _c, _d, _e;
                    return ({
                        e: item.id_split.join(''),
                        lang: (_a = item.audio) !== null && _a !== void 0 ? _a : [],
                        name: item.title,
                        season: (_d = (_c = (_b = item.seasonNum) !== null && _b !== void 0 ? _b : item.seasonTitle) !== null && _c !== void 0 ? _c : item.item.seasonNum) !== null && _d !== void 0 ? _d : item.item.seasonTitle,
                        seasonTitle: item.seasonTitle,
                        episode: item.episodeNum,
                        id: item.id,
                        img: item.thumb,
                        description: item.synopsis,
                        time: (_e = item.runtime) !== null && _e !== void 0 ? _e : item.item.runtime
                    });
                }) };
        });
    }
    handleDefault(name) {
        return __awaiter(this, void 0, void 0, function* () {
            return (0, module_args_1.getDefault)(name, this.funi.cfg.cli);
        });
    }
    availableDubCodes() {
        return __awaiter(this, void 0, void 0, function* () {
            const dubLanguageCodesArray = [];
            for (const language of module_langsData_1.languages) {
                if (language.funi_locale)
                    dubLanguageCodesArray.push(language.code);
            }
            return [...new Set(dubLanguageCodesArray)];
        });
    }
    availableSubCodes() {
        return __awaiter(this, void 0, void 0, function* () {
            return module_langsData_1.subtitleLanguagesFilter;
        });
    }
    resolveItems(data) {
        return __awaiter(this, void 0, void 0, function* () {
            log_1.console.debug(`Got resolve options: ${JSON.stringify(data)}`);
            const res = yield this.funi.getShow(false, Object.assign(Object.assign({}, data), { id: parseInt(data.id) }));
            if (!res.isOk)
                return res.isOk;
            this.addToQueue(res.value.map(a => {
                return Object.assign(Object.assign({}, data), { ids: [a.episodeID], title: a.title, parent: {
                        title: a.seasonTitle,
                        season: a.seasonNumber
                    }, image: a.image, e: a.episodeID, episode: a.epsiodeNumber });
            }));
            return true;
        });
    }
    search(data) {
        return __awaiter(this, void 0, void 0, function* () {
            log_1.console.debug(`Got search options: ${JSON.stringify(data)}`);
            const funiSearch = yield this.funi.searchShow(false, data);
            if (!funiSearch.isOk)
                return funiSearch;
            return { isOk: true, value: funiSearch.value.items.hits.map(a => ({
                    image: a.image.showThumbnail,
                    name: a.title,
                    desc: a.description,
                    id: a.id,
                    lang: a.languages,
                    rating: a.starRating
                })) };
        });
    }
    checkToken() {
        return __awaiter(this, void 0, void 0, function* () {
            return this.funi.checkToken();
        });
    }
    auth(data) {
        return this.funi.auth(data);
    }
    downloadItem(data) {
        return __awaiter(this, void 0, void 0, function* () {
            this.setDownloading(true);
            log_1.console.debug(`Got download options: ${JSON.stringify(data)}`);
            const res = yield this.funi.getShow(false, { all: false, but: false, id: parseInt(data.id), e: data.e });
            const _default = yargs.appArgv(this.funi.cfg.cli, true);
            if (!res.isOk)
                return this.alertError(res.reason);
            for (const ep of res.value) {
                yield this.funi.getEpisode(false, { dubLang: data.dubLang, fnSlug: ep, s: data.id, subs: { dlsubs: data.dlsubs, sub: false, ccTag: _default.ccTag } }, Object.assign(Object.assign({}, _default), { callbackMaker: this.makeProgressHandler.bind(this), ass: true, fileName: data.fileName, q: data.q, force: 'y', noaudio: data.noaudio, novids: data.novids }));
            }
            this.sendMessage({ name: 'finish', data: undefined });
            this.setDownloading(false);
            this.onFinish();
        });
    }
}
exports.default = FunimationHandler;
