angular.module('odoo')

.controller('ConfigurationController', function (
    $scope,
    $state,
    $ionicLoading,
    $ionicPopup,
    userStorageFactory,
    odooInteroperabilityFactory,
    sqlFactory
) {

    // $scope.config = { host: 'localhost', port: 8069, database: 'odoo', username: 'admin', password: 'admin' };
    $scope.config = { host: '192.168.2.106', port: 8069, database: 'odoo', username: 'admin', password: 'admin' };

    $scope.$on('ionicView.enter', function () {
        console.log('Evaluar usuario');
    });

    // Apply configuration for app
    $scope.configure = function () {
        $ionicLoading.show();

        sqlFactory.count('user', function (total) {
            if (total == 0) {
                odooInteroperabilityFactory.auth($scope.config, function (user) {
                    userStorageFactory.save(
                        [
                            user.id,
                            $scope.config.host,
                            $scope.config.port,
                            $scope.config.database,
                            user.username,
                            user.password
                        ], function (newId) {

                            $ionicLoading.hide();
                            $state.go('app.main');
                    }, function (error) {

                        $ionicLoading.hide();
                    });
                }, function (error) {
                    $ionicLoading.hide();

                    var message = 'Configuración no válida';
                    if (angular.isObject(error)) {
                        message = 'No se pudo establecer una llamada al servidor';
                    }

                    $ionicPopup.alert({ title: 'Ha fallado el inicio de sesión', template: message });
                });
            } else {
                $ionicLoading.hide();
                $state.go('app.main');
            }
        }, function (error) {
            $ionicLoading.hide();
        });
    }
});
