/* global confirm */
'use strict';

angular.module('app')
	// .directive('overallInsightEditor', function() {
	// 	return {
	//         template: require('./overall-insight-editor.html'),
	// 		restrict: 'E',
	// 		scope: false,
	// 		controller: OverallInsightEditorCtrl
	// 	};
	// })
	.controller('OverallInsightEditorCtrl',OverallInsightEditorCtrl);



function OverallInsightEditorCtrl($scope, $log, $rootScope, CurrentSession, Insight, User, RealtimeProductResource, notify) {

		var ProductResource = RealtimeProductResource;
		$scope.review=$scope.$parent.$ctrl.review;

		// i shoudl subscribe to an event!
		$rootScope.$on(RealtimeProductResource.getRestEventNames().PUT, function(e, product) {
			$log.info('Some collaborative user changed a product', product);

			var currentProduct;

			currentProduct = CurrentSession.getCurrentProduct();

			if (!product || !currentProduct) {
				return;
			}

			if (product._id !== currentProduct._id) {
				return;
			}

			//CurrentSession.setCurrentProduct(product);
			CurrentSession.getCurrentProduct().insightsDraft = product.insightsDraft;

			// if product is the same of the current product
			// then change otherwise do nothing
			// to change the product, just re-render the insights


			$scope.$apply();
		});

		function isCallCenterData() {
			return $scope.review.review.channel && $scope.review.review.channel.match(/call\-center$/gi) !== null;
		}


		$scope.isLinked = function(insight, reviewId) {
			var isLinked = false;
			isLinked = insight.reviewIds && insight.reviewIds.some(function(aReviewId) {
				return aReviewId === reviewId;
			});
			isLinked = isLinked || (insight.callCenterDataIds && insight.callCenterDataIds.some(function(aReviewId) {
				return aReviewId === reviewId;
			})) || false;
			return isLinked;
		};
		$scope.unlinkInsight = function(insight) {
			var reviewId, product;

			reviewId = $scope.review._id;
			product = CurrentSession.getCurrentProduct();

			ProductResource.unlinkInsightByProductAndInsightAndReviewIdAndIsCallCenterData(product, insight, reviewId, isCallCenterData()).then(function(savedProduct) {
				notify.show('Insight saved!');
				$log.info('Insight saved!', product);
				//savedProduct.language = product.language;
				CurrentSession.getCurrentProduct().insightsDraft = savedProduct.insightsDraft;

			}, function(err) {
				notify.show('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
			});
		};
		$scope.linkInsight = function(insight) {
			var reviewId, product;

			reviewId = $scope.review._id;
			product = CurrentSession.getCurrentProduct();


			ProductResource.linkInsightByProductAndInsightAndReviewIdAndIsCallCenterData(product, insight, reviewId, isCallCenterData()).then(function(savedProduct) {
				notify.show('Insight saved!');
				$log.info('Insight saved!', product);
				savedProduct.language = product.language;
				CurrentSession.getCurrentProduct().insightsDraft = savedProduct.insightsDraft;
				//CurrentSession.setCurrentProduct(savedProduct);
			}, function(err) {
				notify.show('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
			});
		};

		$scope.toggleLink = function(insight) {
			var fieldName;
			var dataSource=CurrentSession.getCurrentProduct().dataSource||'reviews';
			fieldName=(dataSource==='reviews')?'reviewIds':'callCenterDataIds';

			if (insight[fieldName] && insight[fieldName].indexOf($scope.review._id) >= 0) {
				$scope.unlinkInsight(insight);
			} else {
				$scope.linkInsight(insight);
			}
		};
		$scope.addNewInsight = function(text) {
			var insight, product;

			var author;
			var currentUser;

			currentUser = User.get();
			author = (currentUser && currentUser.username) ? currentUser.username : '';


			insight = new Insight({
				text: text,
				reviewIds: ($scope.review && !isCallCenterData()) ? [$scope.review._id] : [],
				callCenterDataIds: ($scope.review && isCallCenterData()) ? [$scope.review._id] : [],
				author: author
			});
			product = CurrentSession.getCurrentProduct();

			ProductResource.addInsightByProductAndInsight(product, insight).then(function(savedProduct) {
				notify.show('Insight saved!');
				$log.info('Insight saved!');
				$scope.isAddingAnInsight = false;
				CurrentSession.getCurrentProduct().insightsDraft = savedProduct.insightsDraft;
				//CurrentSession.getCurrentProduct().insightsDraft = CurrentSession.getCurrentProduct().insightsDraft || [];
				//savedProduct.language = product.language;
				//savedProduct.dataSource = product.dataSource;
				// TODO: is product translated to another format???
				//CurrentSession.setCurrentProduct(savedProduct);

			}, function(err) {
				notify.show('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
			});

		};
		$scope.removeInsight = function(insight) {
			var isConfirmed;
			var product;
			product = CurrentSession.getCurrentProduct();
			isConfirmed = confirm('You could be losing important information. Are you sure? \n If you remove this insight, you will remove all the links of this insight with other reviews.');

			if (isConfirmed) {
				console.log('removing');
				ProductResource.removeInsightByProductAndInsight(product, insight).then(function(savedProduct) {
					console.log('success');
					notify.show('Insight saved!');
					$log.info('Insight saved!');
					$scope.isAddingAnInsight = false;
					savedProduct.language = product.language;
					CurrentSession.setCurrentProduct(savedProduct);
				}, function(err) {
					console.log('error');
					notify.show('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
				});
			}
		};

		$scope.editInsight = function(insight){
			$scope.insightUnderEditing = angular.copy(insight);
		}

		$scope.saveEditInsight = function(insight) {
			var isConfirmed;
			var product;
			product = CurrentSession.getCurrentProduct();
			isConfirmed = confirm('You could be editing important information. Are you sure? \n If you edit this insight, all the linked reviews will be affected.');

			if (isConfirmed) {
				ProductResource.setInsightTextByProductAndOldInsightTextAndNewText(
					product, insight.text, $scope.insightUnderEditing.text)
					.then(function() {
						insight.text = $scope.insightUnderEditing.text;
						notify.show('Insight saved!');
				}, function(err) {
					notify.show('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
				});
			}
		};

		$scope.activeSearch = 'search';

		$scope.open = function() {
			$scope.isInsightsEditorOpen = true;
		};
		$scope.close = function() {
			$scope.isInsightsEditorOpen = false;
		};
		$scope.toggle = function() {
			$scope.isInsightsEditorOpen = !$scope.isInsightsEditorOpen;
		};
		$scope.$on('openInsightsEditor', $scope.open);
		$scope.$on('closeInsightsEditor', $scope.close);
		$scope.$on('toggleInsightsEditor', $scope.toggle);
		$rootScope.$on('selectedText', function(e, selectedText) {
			if (selectedText !== '') {
				$scope.close();
			}
		});

		$scope.isAddingAnInsight = false;
		$scope.currentSession = CurrentSession.get();
		console.log('____',$scope.currentSession);
}