(function()
{
    let moduleName = 'claromentis.project';
    let template = require('../../html/directives/topics_table.directive.html');

    angular.module(moduleName)
        .directive('topicsTable', topicsTable);

    topicsTable.$inject = ['$timeout', '$http', 'topicsPreloadFactory'];
    function topicsTable($timeout, $http, preload)
    {
        return {
            restrict: 'E',
            templateUrl: template,
            scope: {},
            controllerAs: 'ctrl',
            bindToController: true,
            controller: controller,
            link: link
        };

        function controller()
        {
            let ctrl = this;

            this.$onInit = function() {
                ctrl.columns = preload['columns'];
                ctrl.cellTemplates = preload['cell_templates'];
                ctrl.column_defs = preload['column_defs'];
                ctrl.project_id = preload['project_id'];

                // Datatables expects the templates to be in DOM so wait until after the digest ends to flag it as ready to go
                $timeout(function() {
                    ctrl.templates_loaded = true;
                }, 0);
            }

            ctrl.templates_loaded = false;
        }

        function link (scope, element, attrs, controller)
        {
            angular.element(element).on('click', ".pin-toggle", function(event){
                event.preventDefault();

                let $this = angular.element(this);
                let pinUrl = $this.attr('href');
                let pinned = 0;
                if ($this.hasClass('pin-topic'))
                    pinned = 1;

                $http.put(
                    pinUrl,
                    {
                        pinned: pinned
                    }
                ).then(function() {
                    $("#topics-datatable").DataTable().ajax.reload();
                }, function(){});
            });
        }
    }
}());
