import "lightgallery.js";
/**
 *
 */

export default class msMap {
	/**
	 * конструктор
	 * @param {*} options параметры
	 */
	constructor(
		options = {
			mapId: "5cc82180e6b9d406cb074a77",
			templateFolder: "acapella-2019"
		}
	) {
		this.mapId = options.mapId; //id карты с moscowseasons
		this.templateFolder = options.templateFolder; //папка шаблона для пина
		this.showPointInfo = true; //открываем ли пин по клику

		this.clusterer = null;
		this.objectManager = null;
		this.map = null;

		this.dataPoints = {
			items: []
		};

		this.coords = [];

		this.isEventVisible = false;
		this.popup = false;

		this.setBasePath();

		(async () => {
			await this.loadData();
			await this.initMap();
		})();
	}

	/**
	 * задаем пути к пинам
	 */
	setBasePath() {
		this.basePathPin = "/templates/" + this.templateFolder + "/assets/img/ms-map/icon-pin.svg";
		this.basePathPinActive = "/templates/" + this.templateFolder + "/assets/img/ms-map/icon-pin-active.svg";

		if (location.hostname == "localhost") {
			this.basePathPin = "/assets/img/ms-map/icon-pin.svg";
			this.basePathPinActive = "/assets/img/ms-map/icon-pin-active.svg";
		}

		if (location.hostname == "new-year.bnweb.studio") {
			this.basePathPin = "/acapella-2019/assets/img/ms-map/icon-pin.svg";
			this.basePathPinActive = "/acapella-2019/assets/img/ms-map/icon-pin-active.svg";
		}

		if (location.hostname == "www.mos.ru" || location.host == "newmos.mos.ru") {
			this.basePathPin = "https://moscowseasons.com/templates/" + this.templateFolder + "/assets/img/ms-map/icon-pin.svg";
			this.basePathPinActive = "https://moscowseasons.com/templates/" + this.templateFolder + "/assets/img/ms-map/icon-pin-active.svg";
		}
	}

	/**
	 * загружаем данные
	 */
	async loadData() {
		fetch("https://moscowseasons.com/graphql", {
			method: "POST",
			body: JSON.stringify({
				operationName: "map",
				variables: {
					id: this.mapId
				},
				query: `query map ($id: ID) {
						map(id: $id) {
							slug
							layers {
								header
								points {
									address {
										lat
										lon
										address
										__typename
									}
									title
									shortDesc
									event {
										slug
									}
									__typename
								}
								__typename
							}
							__typename
						}
						__typename
					}`
			})
		})
			.then(response => response.json())
			.then(data => {
				console.log("Fetch map data: ", data);
				let id = 1;

				data.data.map.layers.forEach(layer => {
					let points = [];
					let id2 = 1;

					layer.points.forEach(point => {
						if (!point) return;

						points.push({
							id: id2,
							title: point.title ? point.title : "",
							group_id: id,
							lat: point.address.lon,
							lon: point.address.lat,
							address: point.address.address,
							shortDesc: point.shortDesc ? point.shortDesc : null,
							slug: point.event ? point.event.slug : null,
							image: point.image ? point.image.resized.url : null
						});

						this.coords.push(point.address.lat + "_" + point.address.lon);

						id2++;
					});

					this.dataPoints.items.push({
						id: id,
						title: layer.header,
						entity_type: "groups",
						points: points
					});

					id++;
				});
			});
	}

	/**
	 * готовим яндекс карту
	 */
	async initMap() {
		/* global ymaps */
		ymaps.ready(async () => {
			this.map = new ymaps.Map("ms-map__container", {
				center: [55.757, 37.62233],
				zoom: 11
			});

			this.map.margin.addArea({
				left: 0,
				top: 0
			});

			this.objectManager = new ymaps.ObjectManager({
				// Чтобы метки начали кластеризоваться, выставляем опцию.
				clusterize: true,
				// ObjectManager принимает те же опции, что и кластеризатор.
				gridSize: 64,
				// Макет метки кластера pieChart.
				clusterIconLayout: "default#pieChart"
			});

			this.clusterer = new ymaps.Clusterer({
				preset: "islands#invertedRedClusterIcons",
				groupByCoordinates: false,
				zoomMargin: 30,
				clusterDisableClickZoom: false
			});

			let clusterObjects = [];

			let coordsTemp = this.coords.slice();

			this.dataPoints.items.forEach(layer => {
				// Группы точек
				clusterObjects[layer.id] = [];

				layer.points.forEach(point => {
					//console.log(point);

					let lon = Number(point.lon);
					let lat = Number(point.lat);

					coordsTemp = coordsTemp.filter(item => item === point.lon + "_" + point.lat);

					let repeat = coordsTemp.length;

					//console.log(repeat);

					if (!repeat) return;

					let marker = new ymaps.Placemark(
						[lat, lon],
						{
							hintContent: point.address,
							//openEmptyBalloon: false,
							slug: point.slug,
							title: point.title,
							image: point.image,
							address: point.address,
							desc: point.shortDesc
						},
						{
							iconLayout: "default#image",
							iconImageHref: this.basePathPin,
							iconImageSize: [30, 30],
							iconImageOffset: [-15, -15],
							id: point.id,
							balloonPanelMaxMapArea: 0,
							openEmptyBalloon: false
						}
					);

					/* marker.events.add("click", async () => {
						for (var keyLayer in clusterObjects) {
							clusterObjects[keyLayer].forEach(point => {
								point.options.set({
									iconImageHref: this.basePathPin,
									iconImageSize: [30, 30],
									iconImageOffset: [-15, -15]
								});
							});
						}

						marker.options.set({
							iconImageHref: this.basePathPinActive,
							iconLayout: "default#image",
							iconImageSize: [37, 50],
							iconImageOffset: [-18, -25]
						});

						this.map.margin.addArea({
							right: 0,
							bottom: 0
						});

						if (!this.showPointInfo) return false;

						document.querySelector(".ms-map__event-inner").innerHTML = "";

						const wrapElement = document.createElement("div");
						wrapElement.classList.add("ms-map__event-wrap");

						const addressElement = document.createElement("div");
						addressElement.classList.add("ms-map__event-address", "ms-map__event-address--empty");
						addressElement.innerHTML = marker.properties.get("address");

						const descriptionElement = document.createElement("div");
						descriptionElement.classList.add("ms-map__event-dscr");
						descriptionElement.innerHTML = marker.properties.get("title");

						if (marker.properties.get("slug") == null) {
							const imgData = await fetch("https://moscowseasons.com/graphql", {
								method: "POST",
								body: JSON.stringify({
									operationName: "event",
									variables: {
										slug: marker.properties.get("slug"),
										locale: "RU"
									},
									query: `query event($slug: String) {
										event(slug: $slug) {
											...EventFragment
											__typename
										}
									}
									fragment EventFragment on Event {
										...ShortEventFragment
										__typename
									}
									fragment ShortEventFragment on Event {
										id
										locale
										slug
										title
										description
										address {
											address
											__typename
										}
										images {
											id
											url
											resized(width: 500, height: 500) {
												url
												__typename
											}
											__typename
										}
										__typename
									}`
								})
							});
							const img = await imgData.json();
							console.log(img);
						}

						wrapElement.appendChild(addressElement);
						wrapElement.appendChild(descriptionElement);

						document.querySelector(".ms-map__event-inner").appendChild(wrapElement);

						document.querySelector(".ms-map__close").style.display = "block";

						if (window.matchMedia("(max-width: 640px)").matches) {
							// mobile
							if (this.isEventVisible) {
								if (this.popup) {
									this.popup.destroy(true);
									this.popup = null;
									this.isEventVisible = false;
								}
							} else {
								// global lightGallery
								this.popup = lightGallery(document.getElementById("map-event"));
								this.isEventVisible = true;
							}
						} else {
							// desktop
							if (this.isEventVisible) {
								document.querySelector(".ms-map__event").style.display = "none";
							} else {
								document.querySelector(".ms-map__event").style.display = "block";
							}
						}
					});*/

					clusterObjects[layer.id].push(marker);
					this.clusterer.add(marker);
				});

				/* this.map.geoObjects.add(this.clusterer);
				this.objectManager.add(clusterObjects); */
			});

			// удаляем лишние контролы
			this.map.controls.remove("searchControl");
			this.map.controls.remove("geolocationControl");
			this.map.controls.remove("typeSelector");
			this.map.controls.remove("trafficControl");

			if ("ontouchstart" in document.documentElement) {
				this.map.behaviors.disable("drag");
			}

			this.map.controls.remove("fullscreenControl");

			// выключаем зум по скролу
			this.map.behaviors.disable(["scrollZoom"]);

			// автомасштаб
			/* this.map
				.setBounds(this.clusterer.getBounds(), {
					checkZoomRange: true,
					zoomMargin: [20, 20, 20, 20]
				})
				.then(function() {
					//if( map.getZoom() > 15) map.setZoom(15);
				}); */
		});
	}
}
