var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    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) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
import { publish, subscribe } from 'pubsub-js';
import { isExpiredJWT, createPopup, getHost } from '../utils';
import { User } from './user';
import { AuthProvider } from './provider';
var AuthService = /** @class */ (function () {
    function AuthService(app) {
        var _this = this;
        this.SHEETBASE_USER_CHANGED = 'SHEETBASE_USER_CHANGED';
        this.SHEETBASE_USER_INFO = 'user_info';
        this.SHEETBASE_USER_CREDS = 'user_creds';
        this.currentUser = null;
        this.app = app;
        this.Api = this.app.Api
            .addBeforeHooks(function (data) { return __awaiter(_this, void 0, void 0, function () {
            var _a, _b;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!!!this.currentUser) return [3 /*break*/, 2];
                        _a = data.query;
                        _b = 'idToken';
                        return [4 /*yield*/, this.currentUser.getIdToken()];
                    case 1:
                        _a[_b] = _c.sent();
                        _c.label = 2;
                    case 2: return [2 /*return*/, data];
                }
            });
        }); })
            .extend()
            .setEndpoint(this.app.options.authEndpoint || 'auth');
        // initial change state (signin locally)
        setTimeout(function () { return _this.signInWithLocalUser(); }, 1000);
    }
    AuthService.prototype.onAuthStateChanged = function (next) {
        subscribe(this.SHEETBASE_USER_CHANGED, function (msg, user) { return next(user); });
    };
    AuthService.prototype.checkActionCode = function (code) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.Api.get('/oob', { oobCode: code })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.createUserWithEmailAndPassword = function (email, password) {
        return __awaiter(this, void 0, void 0, function () {
            var _a, info, idToken, refreshToken, user;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0: return [4 /*yield*/, this.Api.put('/', {}, {
                            email: email, password: password, offlineAccess: true,
                        })];
                    case 1:
                        _a = _b.sent(), info = _a.info, idToken = _a.idToken, refreshToken = _a.refreshToken;
                        return [4 /*yield*/, this.signIn(info, idToken, refreshToken)];
                    case 2:
                        user = _b.sent();
                        return [2 /*return*/, { user: user }];
                }
            });
        });
    };
    AuthService.prototype.signInWithEmailAndPassword = function (email, password) {
        return __awaiter(this, void 0, void 0, function () {
            var user, _a, info, idToken, refreshToken;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!!!this.currentUser) return [3 /*break*/, 1];
                        user = this.currentUser;
                        return [3 /*break*/, 4];
                    case 1: return [4 /*yield*/, this.Api.post('/', {}, {
                            email: email, password: password, offlineAccess: true,
                        })];
                    case 2:
                        _a = _b.sent(), info = _a.info, idToken = _a.idToken, refreshToken = _a.refreshToken;
                        return [4 /*yield*/, this.signIn(info, idToken, refreshToken)];
                    case 3:
                        user = _b.sent();
                        _b.label = 4;
                    case 4: return [2 /*return*/, { user: user }];
                }
            });
        });
    };
    AuthService.prototype.signInWithCustomToken = function (token) {
        return __awaiter(this, void 0, void 0, function () {
            var user, _a, info, idToken, refreshToken;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!!!this.currentUser) return [3 /*break*/, 1];
                        user = this.currentUser;
                        return [3 /*break*/, 4];
                    case 1: return [4 /*yield*/, this.Api.post('/', {}, {
                            customToken: token, offlineAccess: true,
                        })];
                    case 2:
                        _a = _b.sent(), info = _a.info, idToken = _a.idToken, refreshToken = _a.refreshToken;
                        return [4 /*yield*/, this.signIn(info, idToken, refreshToken)];
                    case 3:
                        user = _b.sent();
                        _b.label = 4;
                    case 4: return [2 /*return*/, { user: user }];
                }
            });
        });
    };
    AuthService.prototype.signInAnonymously = function () {
        return __awaiter(this, void 0, void 0, function () {
            var user, _a, info, idToken, refreshToken;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        if (!!!this.currentUser) return [3 /*break*/, 1];
                        user = this.currentUser;
                        return [3 /*break*/, 4];
                    case 1: return [4 /*yield*/, this.Api.put('/', {}, {
                            offlineAccess: true,
                        })];
                    case 2:
                        _a = _b.sent(), info = _a.info, idToken = _a.idToken, refreshToken = _a.refreshToken;
                        return [4 /*yield*/, this.signIn(info, idToken, refreshToken)];
                    case 3:
                        user = _b.sent();
                        _b.label = 4;
                    case 4: return [2 /*return*/, { user: user }];
                }
            });
        });
    };
    AuthService.prototype.sendPasswordResetEmail = function (email) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.Api.put('/oob', {}, { mode: 'resetPassword', email: email })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.verifyPasswordResetCode = function (code) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.Api.get('/oob', { oobCode: code, mode: 'resetPassword' })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.confirmPasswordReset = function (code, newPassword) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.Api.post('/oob', {}, {
                            oobCode: code,
                            mode: 'resetPassword',
                            newPassword: newPassword,
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.signInWithPopup = function (provider) {
        return __awaiter(this, void 0, void 0, function () {
            var providerConfig, clientId, redirectUri;
            var _this = this;
            return __generator(this, function (_a) {
                if (!this.currentUser) {
                    providerConfig = !!this.app.options.authProviders ?
                        this.app.options.authProviders[provider.providerId] : null;
                    if (!!providerConfig) {
                        // remember provider
                        this.oauthProvider = provider;
                        // add handler to parent window
                        window['handleOauthResult'] = function (fragment) { return _this.handleOauthResult(fragment); };
                        clientId = providerConfig.clientId, redirectUri = providerConfig.redirectUri;
                        return [2 /*return*/, createPopup({
                                url: provider.url(clientId, redirectUri || (getHost() + '/__/auth/handler')),
                            })];
                    }
                }
                return [2 /*return*/];
            });
        });
    };
    AuthService.prototype.googleAuthProvider = function () {
        return new AuthProvider('google.com', 'https://accounts.google.com/o/oauth2/v2/auth', 'https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile');
    };
    AuthService.prototype.facebookAuthProvider = function () {
        return new AuthProvider('facebook.com', 'https://www.facebook.com/v3.2/dialog/oauth', 'email');
    };
    AuthService.prototype.signOut = function () {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        this.currentUser = null;
                        // notify user change
                        publish(this.SHEETBASE_USER_CHANGED, null);
                        // remove user info & id token & refresh token from local
                        return [4 /*yield*/, this.app.Localstorage.remove(this.SHEETBASE_USER_INFO)];
                    case 1:
                        // remove user info & id token & refresh token from local
                        _a.sent();
                        return [4 /*yield*/, this.app.Localstorage.remove(this.SHEETBASE_USER_CREDS)];
                    case 2:
                        _a.sent();
                        return [2 /*return*/];
                }
            });
        });
    };
    AuthService.prototype.signIn = function (info, idToken, refreshToken) {
        return __awaiter(this, void 0, void 0, function () {
            var uid;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        uid = info.uid;
                        this.currentUser = new User(this.Api, info, idToken, refreshToken);
                        // notify user change
                        publish(this.SHEETBASE_USER_CHANGED, this.currentUser);
                        // save user info & id token & refresh token to local
                        return [4 /*yield*/, this.app.Localstorage.set(this.SHEETBASE_USER_INFO, info)];
                    case 1:
                        // save user info & id token & refresh token to local
                        _a.sent();
                        return [4 /*yield*/, this.app.Localstorage.set(this.SHEETBASE_USER_CREDS, { uid: uid, idToken: idToken, refreshToken: refreshToken })];
                    case 2:
                        _a.sent();
                        return [2 /*return*/, this.currentUser];
                }
            });
        });
    };
    AuthService.prototype.signInWithLocalUser = function () {
        return __awaiter(this, void 0, void 0, function () {
            var creds, info, idToken, beenSeconds, expiredUser;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.app.Localstorage.get(this.SHEETBASE_USER_CREDS)];
                    case 1:
                        creds = _a.sent();
                        return [4 /*yield*/, this.app.Localstorage.get(this.SHEETBASE_USER_INFO)];
                    case 2:
                        info = _a.sent();
                        if (!(!!creds && !!info && creds.uid === info.uid)) return [3 /*break*/, 7];
                        idToken = creds.idToken;
                        beenSeconds = (new Date().getTime() - new Date(info.lastLogin).getTime()) / 1000;
                        if (!(beenSeconds > 86400)) return [3 /*break*/, 6];
                        if (!isExpiredJWT(idToken)) return [3 /*break*/, 4];
                        expiredUser = new User(this.Api, info, idToken, creds.refreshToken);
                        return [4 /*yield*/, expiredUser.getIdToken()];
                    case 3:
                        idToken = _a.sent();
                        _a.label = 4;
                    case 4: return [4 /*yield*/, this.Api.get('/user', { idToken: idToken })];
                    case 5:
                        // fetch new info
                        info = _a.sent();
                        _a.label = 6;
                    case 6:
                        // sign user in
                        this.signIn(info, idToken, creds.refreshToken);
                        return [3 /*break*/, 8];
                    case 7:
                        // notify initial state changed
                        publish(this.SHEETBASE_USER_CHANGED, null);
                        _a.label = 8;
                    case 8: return [2 /*return*/];
                }
            });
        });
    };
    AuthService.prototype.handleOauthResult = function (result) {
        return __awaiter(this, void 0, void 0, function () {
            var query, credential, i, _a, key, _b, value, finalValue;
            return __generator(this, function (_c) {
                switch (_c.label) {
                    case 0:
                        if (!(result !== '')) return [3 /*break*/, 3];
                        query = result.substr(1).split('&');
                        credential = {};
                        for (i = 0; i < query.length; i++) {
                            _a = query[i].split('='), key = _a[0], _b = _a[1], value = _b === void 0 ? null : _b;
                            finalValue = value;
                            if (key === 'scope') {
                                finalValue = value.split('%20');
                            }
                            else if (key === 'expires_in') {
                                finalValue = +value;
                            }
                            credential[key] = finalValue;
                        }
                        if (!!credential.access_token) return [3 /*break*/, 1];
                        throw new Error('Sheetbase oauth error!'); // no access token
                    case 1: return [4 /*yield*/, this.processOauthResult(credential)];
                    case 2: return [2 /*return*/, _c.sent()];
                    case 3: return [2 /*return*/];
                }
            });
        });
    };
    AuthService.prototype.processOauthResult = function (credential) {
        return __awaiter(this, void 0, void 0, function () {
            var accessToken, providerId, _a, info, idToken, refreshToken, user;
            return __generator(this, function (_b) {
                switch (_b.label) {
                    case 0:
                        accessToken = credential.access_token;
                        providerId = this.oauthProvider.providerId;
                        return [4 /*yield*/, this.Api.get('/oauth', { providerId: providerId, accessToken: accessToken })];
                    case 1:
                        _a = _b.sent(), info = _a.info, idToken = _a.idToken, refreshToken = _a.refreshToken;
                        return [4 /*yield*/, this.signIn(info, idToken, refreshToken)];
                    case 2:
                        user = _b.sent();
                        return [2 /*return*/, { user: user }];
                }
            });
        });
    };
    return AuthService;
}());
export { AuthService };
