var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, Promise, generator) {
    return new Promise(function (resolve, reject) {
        generator = generator.call(thisArg, _arguments);
        function cast(value) { return value instanceof Promise && value.constructor === Promise ? value : new Promise(function (resolve) { resolve(value); }); }
        function onfulfill(value) { try { step("next", value); } catch (e) { reject(e); } }
        function onreject(value) { try { step("throw", value); } catch (e) { reject(e); } }
        function step(verb, value) {
            var result = generator[verb](value);
            result.done ? resolve(result.value) : cast(result.value).then(onfulfill, onreject);
        }
        step("next", void 0);
    });
};
import { Storage } from '../util/storage';
export class Wordpress {
    constructor() {
        this.model = { menus: {}, params: {}, collections: { post: {} } };
    }
    init(options) {
        const self = this;
        if (typeof window !== 'undefined') {
            window['wp'] = window['wp'] || {};
        }
        return new Promise(function (resolve, reject) {
            self.initApi(options).then(function () {
                if (options.app_server) {
                    self.getParams().then(() => {
                        self.getMenus().then(() => {
                            self.ready = true;
                            resolve();
                        });
                    });
                }
                else {
                    resolve();
                }
            });
        });
    }
    initApi(settings) {
        const self = this;
        this.settings = settings;
        this.endpoint = this.settings.protocol + '//' + this.settings.host + '/index.php/wp-json/';
        return new Promise(function (resolve, reject) {
            if (typeof window !== 'undefined' && !window['WPAPI']) {
                console.error('ERROR: WPAPI is not defined as global');
                reject();
            }
            if (location && location.origin === self.settings.protocol + '//' + self.settings.host) {
                // works only on same domain as wp
                self.discover().then(function () {
                    self.api = new WPAPI({ endpoint: self.endpoint });
                    self.initCustomRoutes();
                    resolve();
                });
            }
            else {
                self.api = new WPAPI({ endpoint: self.endpoint });
                self.initCustomRoutes();
                resolve();
            }
        });
    }
    initCustomRoutes() {
        // app-server plugin
        this.api.params = this.api.registerRoute('app-server/v1', '/params');
        this.api.menus = this.api.registerRoute('app-server/v1', '/menus/(?P<id>[a-zA-Z(-]+)');
        // pods plugin: custom content types
        this.api.apps = this.api.registerRoute('wp/v2', '/apps/(?P<id>\\d+)');
        this.api.iframes = this.api.registerRoute('wp/v2', '/iframes/(?P<id>\\d+)');
    }
    getPosts() {
        const self = this;
        return new Promise(function (resolve, reject) {
            self.api.posts().then(function (posts) {
                const items = [];
                posts.forEach((item) => {
                    if (item.id) {
                        self.model.collections.post[item.id] = item;
                        items.push(item);
                    }
                });
                resolve(items);
            });
        });
    }
    getParams() {
        const self = this;
        return new Promise(function (resolve, reject) {
            self.api.params().then(function (params) {
                self.model.params = params;
                resolve(params);
            });
        });
    }
    getPost(id, type) {
        const self = this;
        if (!this.model.collections[type]) {
            this.model.collections[type] = {};
        }
        return new Promise(function (resolve, reject) {
            function parse(id, type, object) {
                self.model.collections[type][id] = object;
                resolve(object);
            }
            if (self.settings.cache === true && self.model.collections[type][id]) {
                resolve(self.model.collections[type][id]);
            }
            else {
                if (type === 'post') {
                    self.api.posts().id(id).then((res) => parse(id, type, res));
                }
                if (type === 'page') {
                    self.api.pages().id(id).then((res) => parse(id, type, res));
                }
                if (type === 'app') {
                    self.api.apps().id(id).then((res) => parse(id, type, res));
                }
                if (type === 'iframe') {
                    self.api.iframes().id(id).then((res) => parse(id, type, res));
                }
            }
        });
    }
    ;
    getMenu(mid) {
        const self = this;
        return new Promise(function (resolve, reject) {
            self.api.menus().id(mid).then((menu) => {
                self.model.menus[mid] = menu;
                resolve(self.model.menus[mid]);
            });
        });
    }
    getMenus() {
        const self = this;
        return new Promise(function (resolve, reject) {
            const mids = [];
            let i = 0;
            if (!self.model.params.menus.length) {
                resolve(self.model.menus);
                return;
            }
            self.model.params.menus.forEach((menu) => {
                mids.push(menu.slug);
                // mids.push(menu.term_id);
            });
            mids.forEach((mid) => {
                self.getMenu(mid).then(function (menu) {
                    self.model.menus[mid] = menu;
                    i++;
                    if (i === mids.length) {
                        resolve(self.model.menus);
                    }
                });
            });
        });
    }
    saveLocal() {
        Storage.saveLocalModel(this.model, this.model.params.baseUrl);
    }
    restoreLocal() {
        this.model = Storage.restoreLocalModel(this.model.params.baseUrl);
    }
    discover() {
        const self = this;
        const apiPromise = WPAPI.discover(this.settings.protocol + '//' + this.settings.host);
        return new Promise(function (resolve, reject) {
            apiPromise.then(function (site) {
                self.site = site;
                resolve();
            });
        });
    }
}
//# sourceMappingURL=wordpress.js.map