(function () {
    global.dashModule
        .controller('linkSupplierBidsCtrl', ['$scope', '$http', '$', '$translate', 'utilsService', linkSupplierBidsCtrl]);

    function linkSupplierBidsCtrl($scope, $http, $, $translate, utilsService) {
        $scope.getUnlinkedSupplierBids = getUnlinkedSupplierBids();
        $scope.onSupBidSelect = onSupBidSelect;
        $scope.init = init;
        $scope.supplierBids = [];
        $scope.selectedBids = [];
        let existingSelection = [];

        function init(supplierBids){
            existingSelection = supplierBids || [];
        }

        function getUnlinkedSupplierBids(){
            $http({
                method: 'GET',
                url: 'bids/api/getUnlinkedSupplierBids'
            }).then(setUnlinkedSupplierBids, utilsService.onHttpError);
        }

        function setUnlinkedSupplierBids(response){
            if (response.data) {
                $scope.supplierBids = response.data;
                if(existingSelection){
                    existingSelection.forEach((existingSelection) => {
                        const selected = $scope.supplierBids.find((supplierBid) => {
                            return existingSelection.idSupplierBid === supplierBid.idSupplierBid;
                        });
                        onSupBidSelect(selected);
                    });
                }
            }
        }

        function onSupBidSelect(supplierBid){
            const elemPosition = $scope.selectedBids.indexOf(supplierBid);

            if(elemPosition === -1){
                supplierBid.class = 'selected-bid';
                $scope.selectedBids.push(supplierBid);
            }else{
                supplierBid.class = 'not-selected-bid';
                $scope.selectedBids.splice(elemPosition);
            }
        }
    }
})();
