import Swup from 'swup'
import SwupJsPlugin from '@swup/js-plugin'
import SwupPreloadPlugin from '@swup/preload-plugin'
import SwupScrollPlugin from '@swup/scroll-plugin'
// import SwupGaPlugin from '@swup/ga-plugin'

import timelines from '../helpers/timelines'

export default class LoadPagesClass {
	constructor () {
		let animationOptions = []
		setAnimationOptions()

		new Swup({
			containers: ['#main'],
			linkSelector: 'a:not([target="_blank"]):not([href^="#"]):not([href^="mailto:"]):not([tabindex]):not([href*=".pdf"]):not([href*=".zip"]):not([href*=".doc"]):not([href*=".xslx"]):not([href*=".jpg"]):not([href*=".png"]):not([href*=".ppt"]):not([href*=".jpg"]):not([href*=".potx"]):not([href*=".dotx"]):not([href*=".xlsx"]):not([href*=".xls"])',
			cache: true,
			plugins: [
				new SwupPreloadPlugin(),
				new SwupJsPlugin(animationOptions),
				new SwupScrollPlugin({
					doScrollingRightAway: false,
					animateScroll: false
				}),
				// new SwupGaPlugin()
			]
		})

		function setAnimationOptions () {
			animationOptions = [
				{
					from: '(.*)',
					to: '(.*)',
					in: function (next) {
						next()
					},
					out: (next) => {
						let timelinesOut = Object.values(timelines.out)
						let timelinesReverse = Object.values(timelines.reverse)
						let timelineNumber = timelinesOut.length + timelinesReverse.length
						let timelineCounter = 0
						let timelineExist = false

						timelinesOut.forEach(timeline => {
							if (timeline) {
								timeline.play()
								timelineExist = true
								timeline.finished.then(onFinished)
							}
						})

						timelinesReverse.forEach(timeline => {
							if (timeline) {
								timeline.seek(timeline.duration)
								timeline.reverse()
								timeline.completed = false
								timeline.play()
								timelineExist = true
								timeline.finished.then(onFinished)
							}
						})

						function onFinished () {
							timelineCounter++
							if (timelineNumber === timelineCounter) next()
						}

						timelines.reverse = {}
						timelines.out = {}

						if (!timelineExist) next()
					}
				}
			]
		}
	}
}
