'use strict';

/**
 * @ngdoc service
 * @name annotationAppApp.assignedProduct
 * @description
 * # assignedProduct
 * Service in the annotationAppApp.
 */

const MODULE_NAME = 'app';
 
angular.module(MODULE_NAME)
	.service('AssignReviewstoAnalystUtils', function() {


		var Service = {
			encodeAssignedProducts: function(product, choosenLanguage, choosenAnalyst, chosenDataSource) {
				var assignedProducts,
					productId;

				//$log.info('args', arguments);

				assignedProducts = choosenAnalyst.assignedProducts || {};
				assignedProducts = JSON.parse(JSON.stringify(assignedProducts));

				productId = product._id;


				if (Array.isArray(assignedProducts)) {
					choosenAnalyst.assignedProducts = {};
				}

				if (assignedProducts[productId]) {
					assignedProducts[productId].push({
						language: choosenLanguage,
						dataSource: chosenDataSource
					});
				} else {
					assignedProducts[productId] = [{
						language: choosenLanguage,
						dataSource: chosenDataSource
					}];
				}
				assignedProducts = angular.toJson(assignedProducts);
				assignedProducts = angular.fromJson(assignedProducts);

				return assignedProducts;
			},
			decodeAssignedProducts: function(user, products) {
				var result, indexedProducts;
				var assignedProducts;

				assignedProducts=user.assignedProducts;

				if (!assignedProducts || !products) {
					return [];
				}

				indexedProducts = products.reduce(function(acc, product) {
					acc[product._id] = product;
					return acc;
				}, {});

				console.log('indexedProducts', indexedProducts);
				console.log('products', products);

				result = Object.keys(assignedProducts).reduce(function(acc1, productID, index) {

					console.log('productID, index,assignedProducts[productID]', productID, index, assignedProducts[productID]);

					assignedProducts[productID].reduce(function(acc2, assignedProduct) {
						var language, newProduct, dataSource;

						language = assignedProduct.language;
						dataSource = assignedProduct.dataSource;
						assignedProduct = indexedProducts[productID];

						if (!assignedProduct){
							return acc2;
						}

						console.log('assignedProduct', assignedProduct);
						newProduct = JSON.parse(JSON.stringify(assignedProduct));
						newProduct.language = language;
						newProduct.dataSource = dataSource;

						acc2.push(newProduct);


						return acc2;

					}, acc1);

					return acc1;

				}, []);

				return result;

			}
		};
		return Service;


	});
