import { URL_PREFIX, buildUrl,  buildCountUrl, buildDistinctUrl, User } from  './../../../before-each';
/* global buildUrl, buildDistinctUrl */
'use strict';

describe('Controller: AdminProductCatalogCtrl', function() {

	var CatalogController,scope;

	var products, sampledReviews, rawReviews;

	var ProductResource;
	var $httpBackend, $controller;

	beforeEach(inject(function(
			$rootScope, 
			_$controller_, 
			_$httpBackend_,
			_ProductResource_,
			_RawReviews_,
			_Products_,
			_Reviews_
		) {
		$httpBackend = _$httpBackend_;
		scope = $rootScope.$new();
		ProductResource = _ProductResource_;
		products = _Products_;
		rawReviews =  _RawReviews_;
		sampledReviews = _Reviews_;
		$controller = _$controller_;

		var query = {
			'$or': [
				{
					role: 'agent'
				},
				{
					role: 'admin'
				}
			]
		};

		$httpBackend.whenGET(buildUrl('users', query)).respond([{
				username: 'claudia@wonderflow.co'
			}, {
				username: 'chiara@wonderflow.co'
			}]);

		$httpBackend.whenGET(buildUrl('products', {})).respond(200, products);

		$httpBackend.whenGET(buildDistinctUrl({}, 'domain', 'tags')).respond(200, ['d1', 'd2']);

		CatalogController = $controller('CatalogController', {
			$scope: scope
		});

		CatalogController.$onInit();

		scope.$digest();

		$httpBackend.flush();
	}));

	describe('updateAverageRating(...)', function() {

		var updatedProduct;

		beforeEach(function() {
			var query, fields;

			updatedProduct = products[0];
			updatedProduct = JSON.parse(JSON.stringify(updatedProduct));
			updatedProduct.avgRating = 1.3333333333333333;

			query = {
				'appearedOn': {
					'$elemMatch': {
						'title': {
							'$in': [
								't1',
								't2'
							]
						}
					}
				},
			    'rating.value': {
			        '$ne': null
			    },
			    'pubDate': {
			        '$ne': null
			    }
			};

			fields = {
			    'rating': 1,
			    'pubDate': 1
			};

			$httpBackend.whenGET(buildUrl('textcontents', query, null, fields)).respond(200, rawReviews);
			$httpBackend.whenPUT('http://development.api.wonderflow.co/api/enterprise_dashboard_development_data/products/1?&rawOptions=%7B%7D').respond(200, updatedProduct);
			CatalogController.updateAverageRating(products[0], true).then(function(product) {
				updatedProduct = product;
			});
			$httpBackend.flush();
		});

		it('Should update rating based on raw reviews', function() {
			expect(updatedProduct.avgRating).to.be.eql(1.3333333333333333);
		});
	}); 

	describe('updateNumberOfReviews(...)', function() {

		var spy;

		beforeEach(function() {
			spy = sinon.spy(CatalogController.RealtimeProductResource, 'updateNumberOfReviews');
			CatalogController.updateNumberOfReviews(products[0]);
		});

		it('Should update the number of reviews of the selected product', function() {
			expect(spy).to.have.been.called;
		});
	});
});