/// <reference path="//Microsoft.WinJS.1.0/js/ui.js" />
/// <reference path="../../models/customer.js" />
/// <reference path="../../models/dataStorageModel.js" />
/// <reference path="//Microsoft.WinJS.1.0/js/base.js" />
(function () {
    "use strict";
    WinJS.Namespace.define("ViewModel", {
        CustomerData: WinJS.Binding.as({
            customerList: Model.CustomerList,
            numberOfCustomers: null,
            maxID: null,
        }),
        addCustomer: function (firstName, lastName, age, id) {
            return Model.addCustomer(firstName, lastName, age, id);
        },
        addCustomerObject: function (customer) {
            return Model.addCustomer(customer.firstName, customer.lastName, customer.age, customer.id);
        },
        saveCustomer: function (firstName, lastName, age, id) {
            return Samples.Data.insertRecord(
                new Model.Customer(firstName, lastName, age, id));
        },
        addRecords: function (records) {
            records.forEach(function(item) {
                    ViewModel.addCustomerObject(item);
            });
            
        },
 
    });
    ViewModel.CustomerData.customerList.bind("length", function (newVal) {
        if (newVal) {
            ViewModel.CustomerData.numberOfCustomers = newVal;
        }
    });
    function loadData() {
        //Samples.Data.cleanDatabase().done(function (result) {
            Samples.Data.maxID().done(function (id) {
                if (id == 0) {
                    ViewModel.saveCustomer("Philip", "Japikse", 44, id + 1).then(function (id) {
                        ViewModel.saveCustomer("Fred", "Flinstone", 31, id + 1).then(function (id) {
                            ViewModel.saveCustomer("Wilma", "Flinstone", 27, id + 1).then(function (id) {
                                ViewModel.saveCustomer("Betty", "Rubble", 26, id + 1).then(function (id) {
                                    ViewModel.saveCustomer("Joe", "Rockhead", 35, id + 1).then(function (id) {
                                        ViewModel.saveCustomer("Nate", "Slate", 31, id + 1).then(function(id) {
                                            Samples.Data.getCustomers().done(function(results) {
                                                ViewModel.addRecords(results);
                                            });
                                        });
                                    });
                                });
                            });
                        });
                    });
                }
                else {
                    Samples.Data.getCustomers().done(function (results) {
                        ViewModel.addRecords(results);
                    });
                }
            });
        //});
    };
    loadData();
})();