angular.module("app").directive("oosRange", function ($rootScope, $q, SQConstants, L) {
    return {
        restrict: 'E',
        replace: true,
        templateUrl: "../app/directives/oosRange/oosRange.html",
        scope: {
            ranges: '=',
            types: '=',
            rangeData: '=',
            bounds: '=',
            index: '=',
            reloading: '=',
            onRemove: '&',
            onModify: '&'
        },
        link: function (scope, element, attrs) {
            var sampleTypes = SQConstants.getConstants().sampleTypes;

            scope.type = 'isv';

            scope.getTypeLabel = function () {
                var item = getItem(scope.types, "value", scope.type);
                return item ? item.name : '';
            }

            scope.getPartLabel = function () {
                var item = getItem(scope.types, "value", scope.type);
                return item ? item.label + getPartNumber() : scope.type + '?' + getPartNumber();
            }

            function getPartNumber() {
                var number = 0;

                for (var i = 0; i < scope.ranges.length; i++) {
                    if (i == scope.index) break;

                    if (scope.ranges[i].type == scope.type) number++;
                }

                return number + 1;
            }

            scope.onDateFromChange = function (date) {
                var dateFrom = getDate(date);
                var dateTo = getDate(scope.dates.dateTo);

                if (dateTo < dateFrom) return;

                scope.dates.dateFrom = date;
                scope.rangeData.dateFrom = scope.dates.dateFrom;
                scope.onModify();
            }

            scope.onDateToChange = function (date) {
                var dateFrom = getDate(scope.dates.dateFrom);
                var dateTo = getDate(date);

                if (dateTo < dateFrom) return;

                scope.dates.dateTo = date;
                scope.rangeData.dateTo = scope.dates.dateTo;
                scope.onModify();
            }

            scope.onTypeChange = function (type) {
                scope.rangeData.type = scope.type;
                scope.onModify();
            }

            scope.$watch("rangeData", function (newVal) {
                scope.dates = newVal;
                scope.type = newVal.type;
            });
            scope.dates = scope.rangeData;
            scope.type = scope.rangeData.type;
        }
    };
});