angular.module('saveFilterAsGroupDirective', [])
    .directive('saveFilterAsGroup', ['personalGroupsService', 'sharedGroupsService', '$modal', 'inventoryFilterService', function (personalGroupsService, sharedGroupsService, $modal, inventoryFilterService) {
        return {
            restrict: 'A',
            scope: {
                sql: '=',
                disabled: '='
            },
            templateUrl: MP_SITE_URL + '/directives/partials/directive_savefilterasgroup.php',
            link: function ($scope) {
                $scope.saveAsGroupDialog = () => {
                    this.modalInstance = $modal.open({
                        templateUrl: 'saveFilterAsGroupDialog.html',
                        backdrop: 'static',
                        keyboard: true,
                        controller: function($scope, $modalInstance, personalGroupsService, sharedGroupsService, inventoryFilterService, sql) {
                            let self = this;
                            self.groupService = personalGroupsService;

                            $scope.data = {
                                isShared: false,
                                name: '',
                                groupId: undefined
                            };

                            $scope.close = () => {
                                $modalInstance.close('cancel');
                            };

                            $scope.createGroup = () => self.groupService.create({
                                name: $scope.data.name,
                                filter: {
                                    filter: inventoryFilterService.processFilters(sql.filters),
                                    hostFilter: inventoryFilterService.processEntriesFilters(sql),
                                    hostContextInclude: inventoryFilterService.processClassFilters(sql.filters)
                                }
                            }).then(
                                response => $scope.data.groupId = response.data.id,
                                error => notify.error(error.data)
                            );

                            $scope.viewGroup = () => window.location.replace(`/groups/${$scope.data.isShared ? 'shared' : 'personal'}/${$scope.data.groupId}`)

                            $scope.$watch('data.isShared', isShared => {
                                self.groupService = isShared ? sharedGroupsService : personalGroupsService;
                            });
                        },
                        resolve: {
                            personalGroupsService: () => personalGroupsService,
                            sharedGroupsService: () => sharedGroupsService,
                            inventoryFilterService: () => inventoryFilterService,
                            sql: () => $scope.sql
                        }
                    });
                }
            }
        };
    }]);
