/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />  
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />  
/// <reference path="/Telerik.Storage.HTML/js/Telerik.Data.js" />
(function () { 
    "use strict"; 
    WinJS.Namespace.define("Samples.Data", { 
        openDatabase:function() {
            return Telerik.Data.Database.open("Win8Webinar_Data");
        },
        cleanDatabase: function() {
            var db = Samples.Data.openDatabase();
            return db.queryScalar("drop table [customers]").then(function(e) {
                db.close();
            })
        },
        maxID: function () {
            var id = 0;
            var db = Samples.Data.openDatabase();
            return db.queryScalar("select max(id) from customers").then(function (result) {
                id = result ? result : 0;
                db.close();
                return id;
            }, function (error) {
                db.close();
                if (error && error.message) {
                }
                return id;
            });
        },
        getCustomers: function () {
            var db = Samples.Data.openDatabase();
            return db.query("select * from customers").then(function(result) {
                db.close();
                return result;
            }, function (error) {
                db.close();
            });
        },
        deleteCustomer: function(id) {
            var db = Samples.Data.openDatabase();
            db.remove("customers", { id: id });
            db.sync().then(function () {
                db.close();
            });
        },
        deleteCustomerObject: function(customer) {
            var db = Samples.Data.openDatabase();
            db.remove("customers", customer);
            db.sync().then(function () {
                db.close();
            });
        },
        updateCustomer: function (customer) { 
            var temp = Model.Customer.returnSimpleCustomerInfo(customer);
            var db = Samples.Data.openDatabase();
            db.update("customers", temp);
            db.sync().then(function () {
                db.close();
            });
        },
 
        insertRecord: function (customer) {
            var temp = Model.Customer.returnSimpleCustomerInfo(customer);
            var db = Samples.Data.openDatabase();
            db.insert("customers", temp);
            return db.sync().then(function () {
                db.close();
                return customer.id;
            }, function (error) {
                db.close();
                if (error && error.message) {
                }
            })
        },
    });
})();