'use strict';
/* globals by, element, protractor, browser, element */
var selectors = require('./selectors');
var EC = protractor.ExpectedConditions;
module.exports = (function(env) {
	var utils;
	utils = {
		hasClass: function(element, cls) {
			return element.getAttribute('class').then(function(classes) {
				return classes.split(' ').indexOf(cls) !== -1;
			});
		},
		getEndPoint: function() {
			return env.END_POINT;
		},
		goToProductCatalog: function() {
			browser.get(env.END_POINT + '/#/login');
		},
		_getXpathExpressionToClickOnProductCardByProductName: function(productName) {
			var xpathExpr;
			xpathExpr = '(//div[contains(@class,"product-card") and .//h3[contains(text(),"' + productName + '")] ])[1]';
			return xpathExpr;
		},
		_getXpathExpressionForCompareButtonOnProductCardByProductName: function(productName) {
			var xpathExpr;
			xpathExpr = '(//div[contains(@class,"product-card") and .//h3[contains(text(),"' + productName + '")] ]//div[contains(@class,"stats-overlay")]//button)[1]';
			return xpathExpr;
		},
		scrollToMinusOffset: function(element, offset) {
			offset = offset || 100;
			return browser.executeScript('window.scrollTo(0,arguments[0].scrollHeight-' + offset + ');', element.getWebElement());
		},
		login: function(usn, pwd, b) {
			var username, password;
			var browserToUse;

			console.log('options browser is null?', typeof b==='undefined');
			browserToUse = b || browser;

			// browser.pause();
			usn = usn || 'wisse@wonderflow.co';
			pwd = pwd || 'wisse2015';
			// console.log('Maximizing the window...');
			// browser.driver.manage().window().maximize();
			console.log('Going to login', env.END_POINT + '/login');
			
			return browser.driver.manage().window().setSize(1280, 800)
				.then(function() {
					return browserToUse.get(env.END_POINT + '/#/login');
				})
				.then(function() {
					console.log('selecting username and pwd')
					username = browserToUse.element(by.css('input[name="username"]'));
					password = browserToUse.element(by.css('input[name="password"]'));
					console.log('Logging as', usn, pwd);
					return username.clear();
				})
				.then(function() {
					return username.sendKeys(usn);
				})
				.then(function() {
					return username.sendKeys(protractor.Key.TAB);
				})
				.then(function() {
					return password.clear();
				})
				.then(function() {
					return password.sendKeys(pwd);
				})
				.then(function() {
					console.log('Click on login')
					return browserToUse.element(by.css('.btn-login')).click();
				})
				// .then(function(){
				// 	console.log('Wait for /reviews')
				// 	return browserToUse.wait(EC.urlContains('/reviews'), 5000*2,'Waiting ofr URL /reviews');
				// })
				.then(function(){
					console.log('Sleep 2 secs after waited for reviews')
					return browserToUse.sleep(2*1000);
				});
		},
		goToProductDashboardByProductName: function(productName) {
			var self = this;
			return browser.get(env.END_POINT + '/#/product-list').then(function() {
				var el;
				el = element(by.xpath(self._getXpathExpressionToClickOnProductCardByProductName(productName)));
				return browser.driver.wait(protractor.until.elementIsVisible(el)).then(function() {
					return browser.executeScript('arguments[0].scrollIntoView(true)', el.getWebElement()).then(function() {
						return el.click().then(function() {
							return browser.waitForAngular();
						});
					});
				});
			});
		},
		goToProductDashboard: function() {
			var self = this;
			console.log('Going to product dashboard');
			browser.get(env.END_POINT + '/#/product-list');
			return browser.sleep(2 * 1000).then(function() {
				var el;
				// el = element(by.xpath('(//div[contains(@class,"product-card") and .//h3[contains(text(),"AT890/16")] ])[1]'));
				el = element(by.xpath(self._getXpathExpressionToClickOnProductCardByProductName('AT890/16')));
				// el = element(by.xpath('.product-info').first(); el = element.all(by.css('.product-info')).first();
				return browser.driver.wait(protractor.until.elementIsVisible(el)).then(function() {
					return browser.executeScript('arguments[0].scrollIntoView(true)', el.getWebElement()).then(function() {
						return el.click().then(function() {
							return browser.waitForAngular();
						});
					});
				});
				// return browser.executeScript(function(next) {
				//     angular.element(document).scope().$on('masonry.reloaded', function() {
				//         next();
				//     });
				// }).then(function() {
				// });
			});
		},
		goToUsefulReviews: function() {
			var el;
			return utils.goToProductDashboard().then(function() {
				el = element(by.css('.reviewsSubmenuOpeningButton'));
				browser.executeScript('arguments[0].scrollIntoView(true)', el.getWebElement());
				el.click();
				el = element(by.xpath('(//ul[contains(@class,"dashboard")]//a[contains(text(),"Useful reviews")])[1]'));
				browser.driver.wait(protractor.until.elementIsVisible(el)).then(function() {
					console.log('Clicking on sidebar - useful-reviews');
					browser.executeScript('arguments[0].scrollIntoView(true)', el.getWebElement());
					return el.click().then(function() {
						console.log('Waiting for 1 seconds');
						return browser.sleep(1 * 1000);
					});
				});
			});
		},
		goToLocations: function() {
			var el;
			return utils.goToProductDashboard().then(function() {
				el = element(by.css('.reviewsSubmenuOpeningButton'));
				browser.executeScript('arguments[0].scrollIntoView(true)', el.getWebElement());
				el.click();
				el = element(by.xpath('(//ul[contains(@class,"dashboard")]//a[contains(text(),"Geo-location")])[1]'));
				return browser.driver.wait(protractor.until.elementIsVisible(el)).then(function() {
					return browser.executeScript('arguments[0].scrollIntoView(true)', el.getWebElement()).then(function() {
						return el.click().then(function() {
							return browser.waitForAngular();
						});
					});
				});
			});
		},
		goToComparisonSetup: function() {
			console.log('Going to comparison setup...');
			browser.get(env.END_POINT + '/#/comparison');
			return browser.executeScript(function(next) {
				angular.element(document).scope().$on('masonry.created', function() {
					next();
				});
			}).then(function() {
				return browser.waitForAngular();
			});
		},
		goToComparisonSection: function() {
			var self = this;
			console.log('Selecting products (AT890 and AT620) to compare and going to comparison...');
			// var el1, el2, tmp;
			// el1 = element(by.xpath(self._getXpathExpressionToClickOnProductCardByProductName('AT890/16')));
			// browser.executeScript('arguments[0].scrollIntoView(true)', el1.getWebElement());
			// browser.actions().mouseMove(el1.getWebElement()).perform();
			// tmp = element(by.xpath(self._getXpathExpressionForCompareButtonOnProductCardByProductName('AT890/16')));
			// browser.actions().mouseMove(tmp.getWebElement()).perform();
			// browser.driver.wait(protractor.until.elementIsVisible(tmp));
			// tmp.click();
			self.Comparison.selectProductByProductName('AT890/16');
			self.Comparison.selectProductByProductName('AT620/14');
			var submitButton;
			submitButton = element(by.css('.compare-button'));
			return browser.driver.wait(protractor.until.elementIsVisible(submitButton.getWebElement())).then(function() {
				return browser.executeScript('arguments[0].scrollIntoView(true)', submitButton.getWebElement()).then(function() {
					return submitButton.click().then(function() {
						return browser.waitForAngular();
					});
				});
			});
			// // el2 = element(by.xpath('(//h3[contains(text(),"AT620/14")])[1]'));
			// el2 = element(by.xpath(self._getXpathExpressionToClickOnProductCardByProductName('AT620/14')));
			// browser.executeScript('arguments[0].scrollIntoView(true)', el2.getWebElement());
			// return el2.click().then(function() {
			// });
			// });
		},
		goToRelevanceOfDriverSection: function() {
			var el2, el;
			el2 = element(by.xpath('//a[@class="navigation-button" and text()="Drivers"]'));
			return el2.isDisplayed().then(function(isVisible) {
				if (!isVisible) {
					element(by.css('.customerSatistifactionSubmenuOpeningButton')).click();
					browser.driver.wait(protractor.until.elementIsVisible(el2));
				}
				el2.click();
				return browser.waitForAngular();
			});
		},
		goToProsConsSection: function() {
			console.log('Going to "Pros & Cons" section');
			var el2;
			el2 = element(by.xpath('//a[@class="navigation-button" and text()="Pros&Cons"]'));
			return el2.isDisplayed().then(function(isVisible) {
				if (!isVisible) {
					element(by.css('.customerSatistifactionSubmenuOpeningButton')).click();
					browser.driver.wait(protractor.until.elementIsVisible(el2));
				}
				el2.click();
				return browser.waitForAngular();
			});
		},
		goToProductDashboardOfProductAT890: function() {
			var self = this;
			console.log('Going to product dashboard of AT890');
			browser.get(env.END_POINT + '/#/product-list');
			// browser.pause();
			return browser.executeScript(function(next) {
				angular.element(document).scope().$on('masonry.reloaded', function() {
					next();
				});
			}).then(function() {
				var el;
				// el = element(by.xpath('(//h3[contains(text(),"AT890/16")])[1]'));
				el = element(by.xpath(self._getXpathExpressionToClickOnProductCardByProductName('AT890/16')));
				return el.then(function() {
					browser.driver.wait(protractor.until.elementIsVisible(el));
					return browser.executeScript('arguments[0].scrollIntoView(true)', el.getWebElement()).then(function() {
						return el.click().then(function() {
							return browser.waitForAngular();
						});
					});
				});
			});
		},
		ProductCatalogSidebar: {
			group: function(fieldName) {
				var groupingButton;
				fieldName = fieldName || 'priceCategory';
				// click on a group
				// groupingButton = element(by.xpath('(//button[contains(text(),"GROUP")])[1]'));
				groupingButton = element(by.xpath('//button[contains(text(),"GROUP") and preceding-sibling::span[contains(text(),"' + fieldName + '")] ]'));
				return browser.driver.wait(protractor.until.elementIsVisible(groupingButton)).then(function() {
					return utils.scrollToMinusOffset(groupingButton, 50).then(function() {
						return groupingButton.click();
					});
				});
			},
			openProductCatalogSidebar: function() {
				var productCatalogFilterIcon;
				productCatalogFilterIcon = element(by.css('.action-trigger .glyphicon-filter'));
				browser.driver.wait(protractor.until.elementIsVisible(productCatalogFilterIcon));
				browser.executeScript('arguments[0].scrollIntoView(true)', productCatalogFilterIcon.getWebElement());
				productCatalogFilterIcon.click();
				return browser.sleep(1 * 1000);
			},
			closeProductCatalogSidebar: function() {
				return element(by.xpath(selectors.getXpathForClosingButtonForFilteringSidebar())).click();
			},
			filterBy: function(filterValue) {
				element(by.xpath('//div[contains(@class,"productcat-aside")]//label[contains(text(),"' + filterValue + '")]/input')).click();
				return browser.waitForAngular();
			},
			removeFirstActiveFilter: function() {
				var el;
				el = element(by.xpath(selectors.getXpathForRemovingFirstActiveFilter()));
				utils.scrollToMinusOffset(el, 100);
				el.click();
			}
		},
		ProductCatalog: {
			chooseProduct: function() {
				var el;
				el = element(by.xpath(selectors.getXpathSelectorForFirstProductCard()));
				browser.actions().mouseMove(el.getWebElement()).perform();
				// browser.pause();
				element(by.xpath(selectors.getXpathSelectorForFirstCompareButton())).click();
				return browser.waitForAngular();
			},
			chooseGroup: function() {
				var el;
				el = element(by.xpath(selectors.getXpathSelectorForFirstGroupCard())); // by price category
				browser.actions().mouseMove(el.getWebElement()).perform();
				element(by.xpath(selectors.getXpathSelectorForFirstGroupCompareButton())).click();
			}
		},
		Comparison: {
			goingToProsConsComparisonComparingProductVsGroup: function() {
				utils.Comparison.selectFirstProductCard();
				utils.ProductCatalogSidebar.openProductCatalogSidebar();
				utils.ProductCatalogSidebar.group();
				utils.Comparison.selectFirstGroupCard();
				element(by.xpath(selectors.getXpathForSidebarCompareButton())).click();
			},
			goingToRelevanceOfDriverComparisonFromProsConsComparison: function() {
				element(by.xpath('//a[@class="navigation-button" and text()="Relevance of Drivers"]')).click();
			},
			goingToRatingsComparisonFromProsConsComparison: function() {
				element(by.xpath('//a[@class="navigation-button" and text()="Ratings"]')).click();
			},
			selectFirstProductCard: function() {
				var el1, tmp;
				el1 = element(by.xpath(selectors.getXpathSelectorForFirstProductCard()));
				browser.executeScript('arguments[0].scrollIntoView(true)', el1.getWebElement());
				browser.actions().mouseMove(el1.getWebElement()).perform();
				tmp = element(by.xpath(selectors.getXpathSelectorForFirstCompareButton()));
				browser.actions().mouseMove(tmp.getWebElement()).perform();
				browser.driver.wait(protractor.until.elementIsVisible(tmp));
				tmp.click();
				return browser.waitForAngular();
			},
			selectFirstGroupCard: function() {
				var el1, tmp;
				el1 = element(by.xpath(selectors.getXpathSelectorForFirstGroupCard()));
				browser.executeScript('arguments[0].scrollIntoView(true)', el1.getWebElement());
				browser.actions().mouseMove(el1.getWebElement()).perform();
				tmp = element(by.xpath(selectors.getXpathSelectorForFirstGroupCompareButton()));
				browser.actions().mouseMove(tmp.getWebElement()).perform();
				browser.driver.wait(protractor.until.elementIsVisible(tmp));
				tmp.click();
				return browser.waitForAngular();
			},
			selectProductByProductName: function(productName) {
				var self = utils;
				var el1, tmp;
				el1 = element(by.xpath(self._getXpathExpressionToClickOnProductCardByProductName(productName)));
				browser.executeScript('arguments[0].scrollIntoView(true)', el1.getWebElement());
				browser.actions().mouseMove(el1.getWebElement()).perform();
				tmp = element(by.xpath(self._getXpathExpressionForCompareButtonOnProductCardByProductName(productName)));
				browser.actions().mouseMove(tmp.getWebElement()).perform();
				browser.driver.wait(protractor.until.elementIsVisible(tmp));
				tmp.click();
				return browser.waitForAngular();
			}
		},
		UiSelect: function(elem) {
			var self = this;

			self._input = elem;
			self._selectInput = self._input.element(by.css('.ui-select-search'));
			self._choices = self._input.all(by.css('.ui-select-choices-row .ui-select-choices-row-inner'));

			self.sendKeys = function(val) {
				var EC = protractor.ExpectedConditions;
				browser.wait(EC.visibilityOf(self._input), 5000);
				self._input.click();
				self._selectInput.clear();
				return self._selectInput.sendKeys(val);
			};

			self.performClick = function() {
				var EC = protractor.ExpectedConditions;
				browser.wait(EC.visibilityOf(self._input), 5000);
				return self._input.click();
			}

			self.pickChoice = function(index) {
				browser.waitForAngular();
				expect(self._choices.count()).not.toBeLessThan(index + 1);
				var EC = protractor.ExpectedConditions;
				var choice = self._choices.get(index);
				browser.wait(EC.visibilityOf(choice), 5000);
				return choice.click();
			};

			self.getChoicesCount = function() {
				return self._choices.count();
			}
		}

	};
	return utils;
})(require('./env'));
// dovrei passare un parametro e fare il bind