/**
 * ngTable: Table + Angular JS
 *
 * @author Vitalii Savchuk <esvit666@gmail.com>
 * @url https://github.com/esvit/ng-table/
 * @license New BSD License <http://creativecommons.org/licenses/BSD/>
 */

import { IAugmentedJQuery, IAttributes, IDirective, IParseService } from 'angular';
import { TableScope } from './ngTableController';
import { ColumnDef } from './public-interfaces';

/**
 * @private
 */
interface InputAttributes extends IAttributes {
    ngTableColumnsBinding: string;
}

ngTableColumnsBinding.$inject = ["$parse"];

/**
 * One-way data binds the $columns array generated by ngTable/ngTableDynamic to the specified
 * expression.
 * This allows the $columns array created for the table to be accessed outside of the html table
 * markup.
 * 
 * @ngdoc directive
 * 
 * @example
 * ```html
 * <table ng-table="$ctrl.tableParams" class="table" ng-table-columns-binding="$ctlr.tableColumns">
 * ```
 */
export function ngTableColumnsBinding<T>($parse: IParseService) : IDirective {
    const directive = {
        restrict: 'A',
        link: linkFn
    };
    return directive;

    function linkFn($scope: TableScope<T>, $element: IAugmentedJQuery, $attrs: InputAttributes){
        const setter = $parse($attrs.ngTableColumnsBinding).assign;
        if (setter){
            $scope.$watch<ColumnDef[]>('$columns', newColumns => {
                const shallowClone = (newColumns || []).slice(0);
                setter($scope, shallowClone);
            });
        }
    }
}