let StoresAPPController = {
	user: null,
	APK_appInfo: null,
	APK_appInfoComments: null,
	iOS_appInfo: null,
	iOS_appInfoComments: null,
	googleReviewData: [],
	appleReviewData: [],

	reset() {
		let self = this;

		self.user = null;
		self.APK_appInfo = null;
		self.APK_appInfoComments = null;
		self.iOS_appInfo = null;
		self.iOS_appInfoComments = null;
		self.googleReviewData = [];
		self.appleReviewData = [];
	},

	setEvents() {
		let self = this;
		self.reset();

		// Reducción de Header
		headerSectionHeight(0);

		// Añadir titulo
		$('#page-title').text(pf.const.language.RSC1804);

		self.loadLang();

		// Datos de usuario administrador
		self.user = JSON.parse(sessionStorage['STCMBackEnd:user']);

		if(self.user.location == '' || self.user.location == undefined) {
			$('#googleContainer').hide();
			$('#appleContainer').hide();

			// Mensaje de aviso
			let warningTitle = pf.const.language.RSC1804;
			let warningContent = pf.const.language.RSC1805;
			pf.utils.showInfoDialog(warningTitle, warningContent);
		} else {
			self.getAppInfoStore();
		}

		$('#appleSeeFourReviews').hide();

		// Collapse
		addEventArrowTableHeader();
	},

	loadLang() {
		pf.rsc.translateByTag('text');
	},

	getAppInfoStore() {
		let self = this;

		let countryArray = self.user.location.split('-');
		let country = countryArray[1].toLowerCase();

		let parameters = {
			locale: self.user.location,
			country: country
		};
		ajaxComunCallWithCallback('getAppInfoStore', parameters, function(ajaxReturn) {
			if(ajaxReturn) {
				self.APK_appInfo = ajaxReturn.APK_appInfo;
				self.APK_appInfoComments = ajaxReturn.APK_appInfoComments;
				self.iOS_appInfo = ajaxReturn.iOS_appInfo;
				self.iOS_appInfoComments = ajaxReturn.iOS_appInfoComments;

				if(Array.isArray(self.APK_appInfo) && self.APK_appInfo.length === 0) {
					$('#googleContainer').hide();
				} else {
					self.renderGoogleStore();
				}

				if(Array.isArray(self.iOS_appInfo) && self.iOS_appInfo.length === 0) {
					$('#appleContainer').hide();
				} else {
					if(Array.isArray(self.iOS_appInfo.results) && self.iOS_appInfo.results.length === 0) {
						$('#appleContainer').hide();
					} else {
						self.renderAppleStore();
					}
				}
			}
		});
	},

	renderGoogleStore() {
		let self = this;

		// Cabecera
		$('#googleAppLogo').attr('src', self.APK_appInfo.icon);
		$('#googleAppLogo').one('error', function() {
			$('#googleAppLogo').attr('src', stcm.const.downloads + 'logo_g.webp');
		});
		$('#googleMainTitle').text(self.APK_appInfo.name);
		$('#googleMainName').text(self.APK_appInfo.developer.name);
		$('#googlePegi').text(self.APK_appInfo.contentRating);

		// Star rating
		let starRating = self.APK_appInfo.score.toFixed(1);
		$('#googleStarsRating').attr('style', '--rating: ' + starRating + ';');
		let starRatingText = starRating + ' • ' + self.APK_appInfo.numberVoters + ' ' + pf.const.language.RSC1819;
		$('#googleStarsRatingText').text(starRatingText);

		// Imágenes
		$('#googleImg1').attr('src', self.APK_appInfo.screenshots[0]);
		$('#googleImg1').one('error', function() {
			$('#googleImg1').attr('src', stcm.const.downloads + 'img_g_1.webp');
		});
		$('#googleImg2').attr('src', self.APK_appInfo.screenshots[1]);
		$('#googleImg2').one('error', function() {
			$('#googleImg2').attr('src', stcm.const.downloads + 'img_g_2.webp');
		});
		$('#googleImg3').attr('src', self.APK_appInfo.screenshots[2]);
		$('#googleImg3').one('error', function() {
			$('#googleImg3').attr('src', stcm.const.downloads + 'img_g_3.webp');
		});
		$('#googleImg4').attr('src', self.APK_appInfo.screenshots[3]);
		$('#googleImg4').one('error', function() {
			$('#googleImg4').attr('src', stcm.const.downloads + 'img_g_4.webp');
		});

		// Información
		$('#googleInfo').text(self.APK_appInfo.description);

		// Collapse
		$('#infoGoogleCollapse').text(pf.const.language.RSC1806);
		$('#infoGoogleCollapse').on('click', function() {
			if($('#infoGoogleCollapse').text() === pf.const.language.RSC1806) {
				$('#infoGoogleCollapse').text(pf.const.language.RSC1807);
			} else {
				$('#infoGoogleCollapse').text(pf.const.language.RSC1806);
			}
		});

		// Valoraciones y reseñas
		let googleRating = `<span class="fs-60">${self.APK_appInfo.score.toFixed(1)}</span> / 5`;
		$('#googleRating').html(googleRating);

		// Provisional hasta ver como devuelve más reseñas
		let cardsContainer = [];
		for(let element in self.APK_appInfo.reviews) {
			let cardElement = self.APK_appInfo.reviews[element];

			let stars = `<ul class="nav mb-2">`;
			for(let s = 0; s < 5; s++) {
				let color = '';
				if(s < parseInt(cardElement.score)) {
					color = 'gold';
				} else {
					color = 'grey';
				}

				stars += `
					<li class="mr-1">
						<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="${color}" class="bi bi-star-fill" viewBox="0 0 16 16">
							<path d="M3.612 15.443c-.386.198-.824-.149-.746-.592l.83-4.73L.173 6.765c-.329-.314-.158-.888.283-.95l4.898-.696L7.538.792c.197-.39.73-.39.927 0l2.184 4.327 4.898.696c.441.062.612.636.282.95l-3.522 3.356.83 4.73c.078.443-.36.79-.746.592L8 13.187l-4.389 2.256z"/>
						</svg>
					</li>
				`;
			}
			stars += `</ul>`;

			let dataArray = cardElement.date.split('T');
			let data = dataArray[0].split('-');
			let dataFormat = data[2] + '/' + data[1] + '/' + data[0];
			let reviewData = cardElement.userName + ', ' + dataFormat;
			let reviewRowContainer = `
				<div class="card bg-light mb-3">
					<div class="card-body">
						<div>
							<!-- Star rating -->
							${stars}

							<p>${reviewData}</p>
						</div>

						<div>
							<p class="card-text">${cardElement.text}</p>
						</div>
					</div>
				</div>
			`;

			cardsContainer.push(reviewRowContainer);

			let obj = {
				nameUser: cardElement.userName,
				date: dataFormat,
				score: cardElement.score,
				text: cardElement.text
			};
			self.googleReviewData.push(obj);
		}

		let cardsReview = '';
		let reviewSize = cardsContainer.length;
		for(let c = 0; c < reviewSize; c++) {
			cardsReview += cardsContainer[c];
		}

		$('#googleRatingCards').html(cardsReview);

		// Información adicional
		let updateArray = self.APK_appInfo.updated.split('+');
		let update = updateArray[0].replace('T', ' ');
		$('#googleUpdated').text(update);
		$('#googleSize').text(self.APK_appInfo.size);
		$('#googleDownloads').text(self.APK_appInfo.installs);
		$('#googleVersion').text(self.APK_appInfo.appVersion);
		$('#googleRequires').text(self.APK_appInfo.androidVersion);
		$('#googleClassification').text(self.APK_appInfo.contentRating);
	},

	renderAppleStore() {
		let self = this;

		// Cabecera
		$('#appleAppLogo').attr('src', self.iOS_appInfo.results[0].artworkUrl512);
		$('#appleMainTitle').text(self.iOS_appInfo.results[0].trackCensoredName);
		$('#applePegi').text(self.iOS_appInfo.results[0].contentAdvisoryRating);
		$('#appleMainName').text(self.iOS_appInfo.results[0].artistName);

		// Star rating
		let starRating = self.iOS_appInfo.results[0].averageUserRatingForCurrentVersion.toFixed(1);
		$('#appleStarsRating').attr('style', '--rating: ' + starRating + ';');
		let starRatingText = starRating + ' • ' + self.iOS_appInfo.results[0].userRatingCountForCurrentVersion + ' ' + pf.const.language.RSC1819;
		$('#appleStarsRatingText').text(starRatingText);

		// Imágenes
		$('#appleImg1').attr('src', self.iOS_appInfo.results[0].screenshotUrls[0]);
		$('#appleImg2').attr('src', self.iOS_appInfo.results[0].screenshotUrls[1]);
		$('#appleImg3').attr('src', self.iOS_appInfo.results[0].screenshotUrls[2]);
		$('#appleImg4').attr('src', self.iOS_appInfo.results[0].screenshotUrls[3]);

		// Información
		$('#appleInfo').text(self.iOS_appInfo.results[0].description);

		// Collapse
		$('#infoAppleCollapse').text(pf.const.language.RSC1806);
		$('#infoAppleCollapse').on('click', function() {
			if($('#infoAppleCollapse').text() === pf.const.language.RSC1806) {
				$('#infoAppleCollapse').text(pf.const.language.RSC1807);
			} else {
				$('#infoAppleCollapse').text(pf.const.language.RSC1806);
			}
		});

		// Valoraciones y reseñas
		let appleRating = `<span class="fs-60">${self.iOS_appInfo.results[0].averageUserRatingForCurrentVersion.toFixed(1)}</span> / 5`;
		$('#appleRating').html(appleRating);

		// Reseñas
		for(let element in self.iOS_appInfoComments.feed.entry) {
			let cardElement = self.iOS_appInfoComments.feed.entry[element];

			let dataArray = cardElement.updated.label.split('T');
			let data = dataArray[0].split('-');
			let dataFormat = data[2] + '/' + data[1] + '/' + data[0];

			let obj = {
				nameUser: cardElement.author.name.label,
				date: dataFormat,
				score: cardElement['im:rating'].label,
				title: cardElement.title.label,
				text: cardElement.content.label
			};
			self.appleReviewData.push(obj);
		}

		// Ver las primeras cuatro reseñas
		self.appleReviews(true);

		if(self.appleReviewData.length > 4) {
			$('#appleSeeAllReviews').on('click', function() {
				// Ver todas las reseñas
				self.appleReviews(false);
				$('#appleSeeAllReviews').hide();
				$('#appleSeeFourReviews').show();
			});

			$('#appleSeeFourReviews').on('click', function() {
				// Ver las primeras cuatro reseñas
				self.appleReviews(true);
				$('#appleSeeAllReviews').show();
				$('#appleSeeFourReviews').hide();
			});
		} else {
			$('#appleSeeAllReviews').hide();
		}

		// Información
		$('#appleSuplier').text(self.iOS_appInfo.results[0].sellerName);
		let appleSizeM = (parseInt(self.iOS_appInfo.results[0].fileSizeBytes) / 1000000).toFixed(1);
		$('#appleSize').text(appleSizeM + ' MB');
		$('#appleCategory').text(self.iOS_appInfo.results[0].primaryGenreName);
		// Requiere iOS XXX o posterior
		$('#appleCompatibility').text(pf.const.language.RSC1824 + ' iOS ' + self.iOS_appInfo.results[0].minimumOsVersion + ' ' + pf.const.language.RSC1825);
		$('#appleLanguages').text(self.iOS_appInfo.results[0].languageCodesISO2A.join(', '));
		$('#appleAge').text(self.iOS_appInfo.results[0].trackContentRating);
		$('#appleCopyright').text('© 2017 ' + self.iOS_appInfo.results[0].sellerName);
	},

	appleReviews(init) {
		let self = this;

		let cardsContainer = [];
		for(let element in self.appleReviewData) {
			let cardElement = self.appleReviewData[element];

			let stars = `<ul class="nav mb-2">`;
			for(let s = 0; s < 5; s++) {
				let color = '';
				if(s < parseInt(cardElement.score)) {
					color = 'gold';
				} else {
					color = 'grey';
				}

				stars += `
					<li class="mr-1">
						<svg xmlns="http://www.w3.org/2000/svg" width="24px" height="24px" fill="${color}" class="bi bi-star-fill" viewBox="0 0 16 16">
							<path d="M3.612 15.443c-.386.198-.824-.149-.746-.592l.83-4.73L.173 6.765c-.329-.314-.158-.888.283-.95l4.898-.696L7.538.792c.197-.39.73-.39.927 0l2.184 4.327 4.898.696c.441.062.612.636.282.95l-3.522 3.356.83 4.73c.078.443-.36.79-.746.592L8 13.187l-4.389 2.256z"/>
						</svg>
					</li>
				`;
			}
			stars += `</ul>`;

			let reviewData = cardElement.nameUser + ', ' + cardElement.date;
			let reviewRowContainer = `
				<div class="card bg-light mb-3">
					<div class="card-body">
						<div>
							<!-- Star rating -->
							${stars}

							<p>${reviewData}</p>
						</div>

						<div>
							<p class="card-text">
								<strong>${cardElement.title}</strong><br>
								${cardElement.text}
							</p>
						</div>
					</div>
				</div>
			`;

			cardsContainer.push(reviewRowContainer);
		}

		let cardsReview = '';
		let reviewSize = cardsContainer.length;
		for(let c = 0; c < reviewSize; c++) {
			cardsReview += cardsContainer[c];
			if(init && c === 3) {
				break;
			}
		}

		$('#appleRatingCards').html(cardsReview);
	}
};