angular.module('groupsDirective', [])
    .directive('selectGroup', ['personalGroupsService', 'sharedGroupsService', function (personalGroupsService, sharedGroupsService) {
        return {
            restrict: 'A',
            scope: {
                selectedGroup: '='
            },
            templateUrl: MP_SITE_URL + '/directives/partials/directive_selectgroup.php',
            link: function ($scope) {
                $scope.groups = {personal: [], shared: []}
                $scope.selectGroupData = {};

                const params = $.param({
                    skip: 0,
                    limit: 1000
                });

                sharedGroupsService.list(params).then(response => $scope.groups.shared = response.data.data);
                personalGroupsService.list(params).then(response => $scope.groups.personal = response.data.data);

                $scope.$watch('selectedGroup', selectedGroup => {
                    if (!selectedGroup) {
                        $scope.selectGroupData = undefined;
                        return;
                    }
                    const groupService = selectedGroup.type === 'shared' ? sharedGroupsService : personalGroupsService;
                    groupService.get(selectedGroup.id).then(response => {
                        $scope.selectGroupData = response.data;
                    })
                });

                $scope.selectGroup = group => {
                    $scope.selectedGroup = {id: group.id, type: group.type};
                }
            }
        };
    }]);
