'use strict';
/* globals confirm, angular */
// TODO: search for $scope

class OverallInsightsEditorController {

	constructor($log, $rootScope,$scope, RealtimeProductResource, CurrentSession, notify, User, Insight) {
		'ngInject';
		this.$log = $log;
		this.$rootScope = $rootScope;
		this.$scope=$scope;


		this.ProductResource = RealtimeProductResource;
		this.RealtimeProductResource=RealtimeProductResource;
		this.CurrentSession = CurrentSession;
		this.notify = notify;
		this.User = User;
		this.Insight = Insight;

	}

	$onInit() {
		this.activeSearch = 'search';
		this.bindEvents();
		this.$rootScope.$on('openInsightsEditor', this.open);
		this.$rootScope.$on('closeInsightsEditor', this.close);
		this.$rootScope.$on('toggleInsightsEditor', () => {
			this.toggle();
		});
		this.$rootScope.$on('selectedText', (e, selectedText) => {
			if (selectedText !== '') {
				this.close();
			}
		});
		this.isAddingAnInsight = false;
		this.currentSession = this.CurrentSession.get();
		console.log('____', this.currentSession);
	}

	bindEvents() {
		this.$rootScope.$on(this.RealtimeProductResource.getRestEventNames().PUT, (e, product) => {
			this.$log.info('Some collaborative user changed a product', product);
			var currentProduct;
			currentProduct = this.CurrentSession.getCurrentProduct();
			if (!product || !currentProduct) {
				return;
			}
			if (product._id !== currentProduct._id) {
				return;
			}
			//CurrentSession.setCurrentProduct(product);
			this.CurrentSession.getCurrentProduct().insightsDraft = product.insightsDraft;
			this.$scope.$apply();
		});
	}

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

	isLinked(insight, reviewId) {
		var isLinked = false;
		isLinked = insight.reviewIds && insight.reviewIds.some((aReviewId)=> {
			return aReviewId === reviewId;
		});
		isLinked = isLinked || (insight.callCenterDataIds && insight.callCenterDataIds.some((aReviewId)=> {
			return aReviewId === reviewId;
		})) || false;
		return isLinked;
	}

	unlinkInsight(insight) {
		var reviewId, product;
		reviewId = this.review._id;
		product = this.CurrentSession.getCurrentProduct();
		this.ProductResource.unlinkInsightByProductAndInsightAndReviewIdAndIsCallCenterData(product, insight, reviewId, this.isCallCenterData()).then((savedProduct) =>{
			this.notify('Insight saved!');
			this.$log.info('Insight saved!', product);
			//savedProduct.language = product.language;
			this.CurrentSession.getCurrentProduct().insightsDraft = savedProduct.insightsDraft;
		}, (err)=> {
			this.notify('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
		});
	}

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

	toggleLink(insight) {
		var fieldName;
		var dataSource = this.CurrentSession.getCurrentProduct().dataSource || 'reviews';
		fieldName = (dataSource === 'reviews') ? 'reviewIds' : 'callCenterDataIds';
		if (insight[fieldName] && insight[fieldName].indexOf(this.review._id) >= 0) {
			this.unlinkInsight(insight);
			return;
		}
		this.linkInsight(insight);
	}

	addNewInsight(text) {
		var insight, product;
		var author;
		var currentUser;
		currentUser = this.User.get();
		author = (currentUser && currentUser.username) ? currentUser.username : '';
		insight = new this.Insight({
			text: text,
			reviewIds: (this.review && !this.isCallCenterData()) ? [this.review._id] : [],
			callCenterDataIds: (this.review && this.isCallCenterData()) ? [this.review._id] : [],
			author: author
		});
		product = this.CurrentSession.getCurrentProduct();
		this.ProductResource.addInsightByProductAndInsight(product, insight).then((savedProduct)=> {
			this.notify('Insight saved!');
			this.$log.info('Insight saved!');
			this.isAddingAnInsight = false;
			this.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);
		}, (err)=> {
			this.notify('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
		});
	}

	removeInsight(insight) {
		var isConfirmed;
		var product;
		product = this.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');
			this.ProductResource.removeInsightByProductAndInsight(product, insight).then((savedProduct)=> {
				console.log('success');
				this.notify('Insight saved!');
				this.$log.info('Insight saved!');
				this.isAddingAnInsight = false;
				savedProduct.language = product.language;
				this.CurrentSession.setCurrentProduct(savedProduct);
			}, (err)=> {
				console.log('error');
				this.notify('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
			});
		}
	}

	editInsight(insight) {
		this.insightUnderEditing = angular.copy(insight);
	}

	saveEditInsight(insight) {
		var isConfirmed;
		var product;
		product = this.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) {
			this.ProductResource.setInsightTextByProductAndOldInsightTextAndNewText(product, insight.text, this.insightUnderEditing.text).then(()=> {
				insight.text = this.insightUnderEditing.text;
				this.notify('Insight saved!');
			}, (err)=> {
				this.notify('Ooooops: error while saving an Insight!' + JSON.stringify(err, null, 4));
			});
		}
	}

	open() {
		this.isInsightsEditorOpen = true;
	}

	close() {
		this.isInsightsEditorOpen = false;
	}

	toggle() {
		this.isInsightsEditorOpen = !this.isInsightsEditorOpen;
	}
}

export default OverallInsightsEditorController;


// 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('Insight saved!');
// 		$log.info('Insight saved!', product);
// 		//savedProduct.language = product.language;
// 		CurrentSession.getCurrentProduct().insightsDraft = savedProduct.insightsDraft;
// 	}, function(err) {
// 		notify('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('Insight saved!');
// 		$log.info('Insight saved!', product);
// 		savedProduct.language = product.language;
// 		CurrentSession.getCurrentProduct().insightsDraft = savedProduct.insightsDraft;
// 		//CurrentSession.setCurrentProduct(savedProduct);
// 	}, function(err) {
// 		notify('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('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('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('Insight saved!');
// 			$log.info('Insight saved!');
// 			$scope.isAddingAnInsight = false;
// 			savedProduct.language = product.language;
// 			CurrentSession.setCurrentProduct(savedProduct);
// 		}, function(err) {
// 			console.log('error');
// 			notify('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('Insight saved!');
// 			}, function(err) {
// 				notify('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);
// }