var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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 { DatabaseDirectService } from './direct';
import { DatabaseServerService } from './server';
import { buildQuery, buildAdvancedFilter } from './filter';
var DatabaseService = /** @class */ (function () {
    function DatabaseService(app) {
        this.app = app;
        this.DatabaseDirect = new DatabaseDirectService(this.app);
        this.DatabaseServer = new DatabaseServerService(this.app);
    }
    DatabaseService.prototype.direct = function () {
        return this.DatabaseDirect;
    };
    DatabaseService.prototype.server = function () {
        return this.DatabaseServer;
    };
    DatabaseService.prototype.all = function (sheet, cacheTime) {
        if (cacheTime === void 0) { cacheTime = 0; }
        return __awaiter(this, void 0, void 0, function () {
            var items, error_1;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        items = [];
                        if (!this.isDirect(sheet)) return [3 /*break*/, 4];
                        _a.label = 1;
                    case 1:
                        _a.trys.push([1, 3, , 4]);
                        return [4 /*yield*/, this.direct().all(sheet, cacheTime)];
                    case 2:
                        items = _a.sent();
                        return [3 /*break*/, 4];
                    case 3:
                        error_1 = _a.sent();
                        return [3 /*break*/, 4];
                    case 4:
                        if (!!items) return [3 /*break*/, 6];
                        return [4 /*yield*/, this.server().all(sheet, cacheTime)];
                    case 5:
                        items = _a.sent();
                        _a.label = 6;
                    case 6: return [2 /*return*/, items];
                }
            });
        });
    };
    DatabaseService.prototype.query = function (sheet, filter, local, cacheTime) {
        if (local === void 0) { local = true; }
        if (cacheTime === void 0) { cacheTime = 0; }
        return __awaiter(this, void 0, void 0, function () {
            var query, advancedFilter, localItems, items, i, length_1, item;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (filter instanceof Function) {
                            advancedFilter = filter;
                        }
                        else {
                            query = buildQuery(filter);
                        }
                        if (!local) return [3 /*break*/, 2];
                        // turn simple query into advanced query
                        if (!advancedFilter) {
                            advancedFilter = buildAdvancedFilter(query);
                        }
                        return [4 /*yield*/, this.all(sheet, cacheTime)];
                    case 1:
                        localItems = _a.sent();
                        items = [];
                        for (i = 0, length_1 = localItems.length; i < length_1; i++) {
                            item = localItems[i];
                            if (!!advancedFilter(item)) {
                                items.push(item);
                            }
                        }
                        return [2 /*return*/, items];
                    case 2:
                        if (!!advancedFilter) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.server().query(sheet, query, cacheTime)];
                    case 3: return [2 /*return*/, _a.sent()];
                    case 4: throw new Error('Can only apply advanced query with local data.');
                }
            });
        });
    };
    DatabaseService.prototype.items = function (sheet, filter, local, cacheTime) {
        if (local === void 0) { local = true; }
        if (cacheTime === void 0) { cacheTime = 0; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, !!filter ? this.query(sheet, filter, local, cacheTime) : this.all(sheet, cacheTime)];
            });
        });
    };
    DatabaseService.prototype.item = function (sheet, finder, local, cacheTime) {
        if (local === void 0) { local = true; }
        if (cacheTime === void 0) { cacheTime = 0; }
        return __awaiter(this, void 0, void 0, function () {
            var item, items;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        item = null;
                        if (!(typeof finder === 'string' && !local)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.server().item(sheet, finder, cacheTime)];
                    case 1:
                        item = _a.sent();
                        return [3 /*break*/, 4];
                    case 2:
                        // turn string into finder
                        if (typeof finder === 'string') {
                            finder = { $key: finder };
                        }
                        return [4 /*yield*/, this.query(sheet, finder, local, cacheTime)];
                    case 3:
                        items = _a.sent();
                        // extract item
                        if ((items || []).length === 1) {
                            item = items[0];
                        }
                        _a.label = 4;
                    case 4: return [2 /*return*/, item];
                }
            });
        });
    };
    DatabaseService.prototype.content = function (contentSource, // doc url | published url
    styles, cacheTime) {
        if (styles === void 0) { styles = 'clean'; }
        if (cacheTime === void 0) { cacheTime = 0; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!this.isDocsContentSourceNotDirectly(contentSource)) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.server().content(contentSource, styles, cacheTime)];
                    case 1: // server
                    return [2 /*return*/, _a.sent()];
                    case 2: return [4 /*yield*/, this.direct().content(contentSource, styles, cacheTime)];
                    case 3: // direct
                    return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DatabaseService.prototype.itemAndContent = function (sheet, finder, item, // loaded item where not sure there is content or not
    styles, local, cacheTime) {
        if (styles === void 0) { styles = 'clean'; }
        if (local === void 0) { local = true; }
        if (cacheTime === void 0) { cacheTime = 0; }
        return __awaiter(this, void 0, void 0, function () {
            var contentData;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        if (!!item) return [3 /*break*/, 2];
                        return [4 /*yield*/, this.item(sheet, finder, local, cacheTime)];
                    case 1:
                        item = _a.sent();
                        _a.label = 2;
                    case 2:
                        if (!(!!item &&
                            !item['content'] &&
                            !!item['contentSource'] &&
                            this.isContentSourceFromDocs(item['contentSource']))) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.content(item['contentSource'], styles, cacheTime)];
                    case 3:
                        contentData = _a.sent();
                        // merge content to item
                        item = __assign({}, item, contentData);
                        _a.label = 4;
                    case 4: 
                    // return final item
                    return [2 /*return*/, item];
                }
            });
        });
    };
    DatabaseService.prototype.set = function (sheet, key, data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.server().set(sheet, key, data)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DatabaseService.prototype.update = function (sheet, key, data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.server().update(sheet, key, data)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DatabaseService.prototype.add = function (sheet, key, data) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.update(sheet, key, data)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DatabaseService.prototype.remove = function (sheet, key) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.update(sheet, key, null)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DatabaseService.prototype.increase = function (sheet, key, increasing) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, this.server().increase(sheet, key, increasing)];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    DatabaseService.prototype.clearCacheAll = function (input) {
        return __awaiter(this, void 0, void 0, function () {
            var i;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0:
                        // turn string to string[]
                        if (typeof input === 'string') {
                            input = [input];
                        }
                        i = 0;
                        _a.label = 1;
                    case 1:
                        if (!(i < input.length)) return [3 /*break*/, 4];
                        return [4 /*yield*/, this.app.Cache.removeByPrefix('database_' + input[i])];
                    case 2:
                        _a.sent();
                        _a.label = 3;
                    case 3:
                        i++;
                        return [3 /*break*/, 1];
                    case 4: return [2 /*return*/];
                }
            });
        });
    };
    DatabaseService.prototype.clearCacheItem = function (sheet, item) {
        return __awaiter(this, void 0, void 0, function () {
            var input, id;
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: 
                    // clear all associated data
                    return [4 /*yield*/, this.clearCacheAll(sheet)];
                    case 1:
                        // clear all associated data
                        _a.sent();
                        input = item['contentSource'];
                        if (!this.isContentSourceFromDocs(input)) return [3 /*break*/, 5];
                        id = '';
                        if (this.isDocsContentSourceNotDirectly(input)) {
                            id = input.replace('https://docs.google.com/document/d/', '').split('/').shift();
                        }
                        else {
                            id = input.replace('/pub', '').split('/').pop();
                        }
                        return [4 /*yield*/, this.app.Cache.removeByPrefix('content_' + id + '_clean')];
                    case 2:
                        _a.sent();
                        return [4 /*yield*/, this.app.Cache.removeByPrefix('content_' + id + '_full')];
                    case 3:
                        _a.sent();
                        return [4 /*yield*/, this.app.Cache.removeByPrefix('content_' + id + '_original')];
                    case 4:
                        _a.sent();
                        _a.label = 5;
                    case 5: return [2 /*return*/];
                }
            });
        });
    };
    DatabaseService.prototype.isDirect = function (sheet) {
        var _a = this.app.options, databaseId = _a.databaseId, databaseGids = _a.databaseGids;
        return !!databaseId && !!databaseGids && !!databaseGids[sheet];
    };
    DatabaseService.prototype.isContentSourceFromDocs = function (input) {
        // must be: not custom | doc url | published url
        return (
        // not intended custom source
        input.indexOf('from:') < 0 &&
            // doc url | published url
            input.indexOf('https://docs.google.com/document/d/') > -1);
    };
    DatabaseService.prototype.isDocsContentSourceNotDirectly = function (input) {
        return (input.indexOf('https://docs.google.com/document/d/e/') < 0 &&
            input.indexOf('/pub') < 0);
    };
    return DatabaseService;
}());
export { DatabaseService };
