angular.module('odoo')

    /**
     *
     */
    .controller('CustomersController', function (
        $scope,
        $ionicModal,
        $ionicActionSheet,
        $ionicPopup,
        customersRemoteFactory,
        customersStorageFactory,
        sqlFactory,
        cameraFactory,
        contactFactory
    ) {
        $scope.loading = false;
        $scope.customers = [];
        $scope.customer = {};

        $ionicModal.fromTemplateUrl('templates/sales/customer.html', {
            scope: $scope,
            animation: 'slide-in-up'
        }).then(function (modal) {
            $scope.customerModal = modal;
        });

        $scope.$on('$ionicView.enter', function () {
            $scope.fill();
        });

        $scope.$on('$destroy', function () {
            $scope.customerModal.remove();
        });

        $scope.$on('modal.hidden', function () {
            $scope.customer = {};
        });

        /**
         *
         */
        $scope.fill = function (refresh = false) {
            $scope.loading = !refresh;

            customersRemoteFactory.sync(function (customers) {
                console.log('Customers sync correctly and receive ' + customers.length + ' items');

                $scope.getCustomers(function () {
                    $scope.$broadcast('scroll.refreshComplete');
                    $scope.loading = false;
                }, function (getCustomersError) {

                    $scope.$broadcast('scroll.refreshComplete');
                    $scope.loading = false;

                    $ionicPopup.alert({ title: 'No se pudo obtener los clientes' });
                });
            }, function (syncErr) {

                $scope.getCustomers(function () {
                    $scope.$broadcast('scroll.refreshComplete');
                    $scope.loading = false;
                }, function (getCustomersError) {

                    $scope.$broadcast('scroll.refreshComplete');
                    $scope.loading = false;

                    $ionicPopup.alert({ title: 'No se pudo obtener los clientes' });
                });
            });
        }

        /**
         *
         */
        $scope.getCustomers = function (success, error) {
            sqlFactory.selectByConstraint('partner', 'customer = 1 AND modified != 2', function (customers) {
                $scope.customers = [];

                for (var i = 0; i < customers.length; i++) {
                    $scope.customers.push(customers.item(i));
                }

                $scope.$apply();
                success();
            }, function (customerGetByConstraintError) {
                error(customerGetByConstraintError);
            });
        }

        /**
         *
         */
        $scope.openOptions = function (index) {
            if (index == -1) {
                $scope.customer = {};
            } else {
                $scope.customer = $scope.customers[index];
            }

            console.log('Customer selected => ' + JSON.stringify($scope.customer));

            $ionicActionSheet.show({
                titleText: 'Acciones',
                buttons: [
                    {
                        text: '<i class="icon ion-arrow-expand positive"></i> Abrir'
                    },
                    {
                        text: '<i class="icon ion-archive positive"></i> Agregar a contactos'
                    }
                ],
                destructiveText: '<i class="icon ion-trash-a assertive"></i> Eliminar',
                cancel: function () {
                    $scope.customer = {};
                    console.log('ActionSheet canceled');
                },
                buttonClicked: function (index) {
                    switch (index) {
                        case 0:
                            $scope.show();
                            break;
                        case 1:
                            $scope.addContact();
                            break;
                        default:
                            $scope.show();
                    }
                    return true;
                },
                destructiveButtonClicked: function () {
                    $scope.delete();

                    return true;
                }
            });
        }

        /**
         *
         */
        $scope.save = function () {
            customersStorageFactory.save($scope.customer, function (customerId) {
                if (!$scope.customer.id) {
                    $scope.customer.id = customerId;
                    $scope.customers.push($scope.customer);
                }

                $scope.customer = {};
                $scope.customerModal.hide();
                console.log('Customer saved');
            }, function (error) {
                $ionicPopup.alert({ title: 'No se ha podido guardar el cliente', template: JSON.stringify(error) });
                console.log(JSON.stringify(error));
            });
        }

        /**
         *
         */
        $scope.delete = function () {
            $ionicPopup.confirm({
                title: 'Confirmar',
                template: 'Estás seguro que quieres eliminar este cliente?'
            }).then(function (confirmation) {
                if (confirmation) {
                    customersStorageFactory.remove($scope.customer, function (affected) {
                        if (affected != 0) {
                            var index = $scope.customers.indexOf($scope.customer);
                            $scope.customers.splice(index, 1);
                            $scope.customer = {};

                            $scope.$apply();
                        }
                    }, function (error) {
                        $ionicPopup.alert({ title: 'No se puedo eliminar el cliente', template: JSON.stringify(error) });
                        console.log(JSON.stringify(error));
                    });
                }
            });
        }

        /**
         *
         */
        $scope.show = function () {
            $scope.customerModal.show();
        }

        /**
         *
         */
        $scope.takePicture = function () {
            cameraFactory.takePicture(function (imageData) {
                $scope.customer.image_small = imageData;
                $scope.customer.image_medium = imageData;
            }, function (error) {
                console.log(error);
            });
        }

        /**
         *
         */
        $scope.addContact = function () {
            contactFactory.save($scope.customer, function (result) {
                $ionicPopup.alert({ title: 'Contacto guardado' });
            }, function (error) {
                console.log(error);
            })
        }
    });
