export default class InsightsController {


    constructor($scope, $location, $stateParams, $log, $filter, $rootScope, $uibModal, $window, RealtimeProductResource, InsightMergeOperation) {
        'ngInject';
				this.$scope = $scope;
				this.$location = $location;
				this.$stateParams = $stateParams;
				this.$log = $log;
				this.$filter = $filter;
				this.$rootScope = $rootScope;
				this.$uibModal = $uibModal;
				this.$window = $window;
				this.RealtimeProductResource = RealtimeProductResource;
				this.InsightMergeOperation = InsightMergeOperation;
    }

    $onInit() {
		this.product = null;
		this.productId = this.$stateParams.productId;
		this.indexOfCurrentInsightToEdit = -1;
		this.activeOps = 0;
		this.isMergeModeActive = false;

		if (!this.productId) {
			return alert('Please provide a productId');
		}

		this.$log.info('>>> Hello, I am InsightsListCtrl!');
		var ProductEventNamesByHttpMethods = this.RealtimeProductResource.getRestEventNames();
		this.$rootScope.$on(ProductEventNamesByHttpMethods.PUT, (e, product) => {
		if (this.product._id === product._id) {
			this.$log.info('Some collaborative user updated a product', product);
			this.bindProductToController(product); 
			this.$scope.$apply();
		}
		});

		this.RealtimeProductResource.getOneById(this.productId)
		.then((product) => {
			this.bindProductToController(product); 
			this.$log.info('>>> Product is', product);
		}, (err) => {
			alert('Error', JSON.stringify(err, null, 4));
		});

    }

	bindProductToController(product) {
		this.product = product;
		angular.forEach(this.product.insightsDraft, (insight, key) => {
			insight.newInsightText = insight.text;
		});
	}


	updateInsightTextByInsightAndNewText(indexOfInsight, newText) {
		var oldText,
			product,
			insights,
			targetInsight;

		this.activeOps = this.activeOps + 1;

		product = this.product;
		insights = product.insightsDraft;
		targetInsight = insights[indexOfInsight];
		if (!targetInsight) {
			alert('Problem saving this insight!');
		}
		oldText = targetInsight.text;
		this.RealtimeProductResource.setInsightTextByProductAndOldInsightTextAndNewText(product, oldText, newText)
			.then( (updatedProduct) => {
				//this.product = updatedProduct;
				insights[indexOfInsight].text = newText;
			})
			.catch((err) => {
				alert('Problem while saving the insight!' + '\n' + JSON.stirngify(err, null, 4));
			})
			.finally( () => {
				this.activeOps = this.activeOps - 1;
			});
	};

	setIndexOfCurrentInsightToEdit(i) {
		this.indexOfCurrentInsightToEdit = i;
	};

	mergeInsights(insights) {
		var insightsToMerge;

		insightsToMerge = insights.filter( (insight) => {
		return insight.isToMerge;
		});
		var uibModalInstance = this.$uibModal.open({
			template: require('./modals/insights-list-merge.html'),
			controller: function($scope, $uibModalInstance, $log, insightMergeOperation) {
				$scope.insightMergeOperation = insightMergeOperation;
				$log.info('$scope.insightMergeOperation', $scope.insightMergeOperation);
				$scope.ok = function() {
					$uibModalInstance.close($scope.insightMergeOperation);
				};
				$scope.cancel = function() {
					$uibModalInstance.dismiss('cancel');
				};
			},
			size: 'lg',
			resolve: {
				insightMergeOperation: () => {
				return new this.InsightMergeOperation({
					insightsToMerge: insightsToMerge,
					newTextOfMergedInsight: '',
					product: this.product
				});
				}
			}
		});

		uibModalInstance.result.then((insightMergeOperation) => {
			this.$log.info('Executing merge of 2 insights', insightMergeOperation);
			return insightMergeOperation.execute();
		})
		.then((doc) => { // 0 result from pullAll, 1 result from push
			this.$log.info('Result from merge...', doc);
			var tmp;
			tmp = doc[0];
			this.product = tmp[tmp.length - 1];
			console.log(doc);
			this.isMergeModeActive = false;
			angular.forEach(this.product.insightsDraft, (insight, key) => {
				insight.newInsightText = insight.text;
			});
		})
		.catch((msg) => {
			this.$log.info('Merge Operation Failed: ' + msg);
		});
	};

	openInsightPreviewModal(product) {
		var uibModalInstance = this.$uibModal.open({
			template: require('./modals/insights-preview.html'),
			controller: function($scope, $uibModalInstance, $filter) {
				$scope.insights = [];
				angular.forEach(product.insightsDraft,function(idraft, key){
					if (idraft.state == 2) {
						idraft.numberOfReviews = idraft.reviewIds.length;
						this.push(idraft);
					}
				}, $scope.insights);
				$scope.modalTitle = 'Pusblished insights for ' + product.brandName + product.productName;
				this.product = product;
				$scope.cancel = function() {
					$uibModalInstance.dismiss('cancel');
				};
			},
			size: 'lg',
			resolve: {
				items: () => {
					return this.items;
				}
			}
		});

		uibModalInstance.result.then((selectedItem) => {
			this.selected = selectedItem;
		}, () => {
			this.$log.info('Modal dismissed at: ' + new Date());
		});
	};

	publishInsight(insight) {
		this.RealtimeProductResource
			.publishInsightByProductIdInsightTextAndCreatedAt(this.product._id, insight.text, insight.createdAt)
			.then( (newProduct) => {
				this.bindProductToController(newProduct); 
			})
			.catch( (msg) => {
				alert('Ooooops: error...' + msg);
			});
	};

	unpublishInsight(insight) {
		this.RealtimeProductResource
			.unpublishInsightByProductIdInsightTextAndCreatedAt(this.product._id, insight.text, insight.createdAt)
			.then( (newProduct) => {
				this.bindProductToController(newProduct); 
			})
			.catch( (msg) => {
				alert('Ooooops: error...' + msg);
			});
	};

	back() {
		this.$window.history.back();
	}

}
