angular.module('odoo')

    /**
     *
     */
    .controller('LeadsController', function (
        $scope,
        $ionicModal,
        $ionicActionSheet,
        $ionicFilterBar,
        $ionicPopup,
        $cordovaVibration,
        leadsRemoteFactory,
        leadsStorageFactory,
        opportunitiesStorageFactory,
        sqlFactory
    ) {

        $scope.loading = false;
        $scope.leads = [];
        $scope.lead = {};
        $scope.conversion = {
            action: 'convert',
            customer: 'create'
        };
        $scope.search = null;


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

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

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

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

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

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

            leadsRemoteFactory.sync(function (leads) {
                console.log('Leads sync correctly and receive ' + leads.length + ' items');

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

                    $ionicPopup.alert({ title: 'No se pudo obtener las iniciativas' });
                });
            }, function (syncErr) {
                $scope.getLeads(function () {
                    $scope.$broadcast('scroll.refreshComplete');
                    $scope.loading = false;
                }, function (getLeadsErr) {
                    $scope.$broadcast('scroll.refreshComplete');
                    $scope.loading = false;

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

        /**
         *
         */
        $scope.getLeads = function (success, error) {
            sqlFactory.selectByConstraint('crm_lead', "type = 'lead' AND modified != 2", function (leads) {
                console.log(leads);
                $scope.leads = [];

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

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

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

        /**
         *
         */
        $scope.save = function () {
            leadsStorageFactory.save($scope.lead, function (leadId) {
                if (!$scope.lead.id) {
                    $scope.lead.id = leadId;
                    $scope.leads.push($scope.lead);
                }

                $scope.lead = {};
                $scope.leadModal.hide();
                console.log('Lead saved');
            }, function (error) {
                $ionicPopup.alert({ title: 'No se ha podido guardar la iniciativa', template: JSON.stringify(error) });
                console.log(JSON.stringify(error));
            });
        }

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

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

        /**
         *
         */
        $scope.convertToOpportunity = function () {
            opportunitiesStorageFactory.save($scope.lead, function (opportunityId) {
                $scope.leadToOpportunityModal.hide();

                var index = $scope.leads.indexOf($scope.lead);
                $scope.leads.splice(index, 1);
                $scope.lead = {};

                $scope.$apply();
            }, function (saveErr) {
                $scope.leadToOpportunityModal.hide();
                $ionicPopup.alert({
                    title: 'No se puedo convertir la iniciativa',
                    template: JSON.stringify(saveErr)
                });
            });
        }

        /**
         *
         */
        $scope.toggleSearch = function () {
            $scope.search = $ionicFilterBar.show({
                items: $scope.leads,
                update: function (filtered, text) {
                    $scope.leads = filtered;
                }
            });
        }

        /**
         *
         */
        $scope.openOptions = function (index) {
            $cordovaVibration.vibrate(100);

            if (index == -1) {
                $scope.lead = {};
            } else {
                $scope.lead = $scope.leads[index];
            }

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

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

                    return true;
                }
            });
        }
    });
