var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
import { StorageEngine } from './storage';
import { defaults, assign } from '../util/util';
var DB_NAME = '__ionicstorage';
var win = window;
export var SqlStorage = (function (_super) {
    __extends(SqlStorage, _super);
    function SqlStorage(options) {
        if (options === void 0) { options = {}; }
        _super.call(this);
        var dbOptions = defaults(options, {
            name: DB_NAME,
            backupFlag: SqlStorage.BACKUP_LOCAL,
            existingDatabase: false
        });
        if (win.sqlitePlugin) {
            var location_1 = this._getBackupLocation(dbOptions.backupFlag);
            this._db = win.sqlitePlugin.openDatabase(assign({
                name: dbOptions.name,
                location: location_1,
                createFromLocation: dbOptions.existingDatabase ? 1 : 0
            }, dbOptions));
        }
        else {
            console.warn('Storage: SQLite plugin not installed, falling back to WebSQL. Make sure to install cordova-sqlite-storage in production!');
            this._db = win.openDatabase(dbOptions.name, '1.0', 'database', 5 * 1024 * 1024);
        }
        this._tryInit();
    }
    SqlStorage.prototype._getBackupLocation = function (dbFlag) {
        switch (dbFlag) {
            case SqlStorage.BACKUP_LOCAL:
                return 2;
            case SqlStorage.BACKUP_LIBRARY:
                return 1;
            case SqlStorage.BACKUP_DOCUMENTS:
                return 0;
            default:
                throw Error('Invalid backup flag: ' + dbFlag);
        }
    };
    SqlStorage.prototype._tryInit = function () {
        this.query('CREATE TABLE IF NOT EXISTS kv (key text primary key, value text)').catch(function (err) {
            console.error('Storage: Unable to create initial storage tables', err.tx, err.err);
        });
    };
    SqlStorage.prototype.query = function (query, params) {
        var _this = this;
        if (params === void 0) { params = []; }
        return new Promise(function (resolve, reject) {
            try {
                _this._db.transaction(function (tx) {
                    tx.executeSql(query, params, function (tx, res) { return resolve({ tx: tx, res: res }); }, function (tx, err) { return reject({ tx: tx, err: err }); });
                }, function (err) { return reject({ err: err }); });
            }
            catch (err) {
                reject({ err: err });
            }
        });
    };
    SqlStorage.prototype.get = function (key) {
        return this.query('select key, value from kv where key = ? limit 1', [key]).then(function (data) {
            if (data.res.rows.length > 0) {
                return data.res.rows.item(0).value;
            }
        });
    };
    SqlStorage.prototype.set = function (key, value) {
        return this.query('insert or replace into kv(key, value) values (?, ?)', [key, value]);
    };
    SqlStorage.prototype.remove = function (key) {
        return this.query('delete from kv where key = ?', [key]);
    };
    SqlStorage.prototype.clear = function () {
        return this.query('delete from kv');
    };
    SqlStorage.BACKUP_LOCAL = 2;
    SqlStorage.BACKUP_LIBRARY = 1;
    SqlStorage.BACKUP_DOCUMENTS = 0;
    return SqlStorage;
}(StorageEngine));
