<script>
import { defineComponent } from 'vue'
import Player from '@/components/Player.vue'
import { config } from '@/main.js'
import { animate, createSpring } from 'animejs'
import Cookies from 'js-cookie'

export default defineComponent({
    name: 'VideoFeed',
    data() {
        return {
            player1: null,
            player2: null,
            config,
            animating: false,
            feedIndex: 0,
            currentPlayer: "player1",
            stiffness: 550,
            damping: 15,
			touchInfo: []
        }
    },
    props: {
        feed: {
            type: Object,
            required: true
        }
    },
    methods: {
        scrollDown() {
            if(this.animating) return;
            if (this.feedIndex >= this.feed.length - 1) {
				if(!this.signedIn()) {
					alert("SIGN IN to see more EPIC content!!!");
					this.animating = false;
					return;
				}
                console.log("Reached end of feed");
                this.animating = false;
                return;
            }

            this.animating = true;
            const screenHeight = window.innerHeight;
            const inactivePlayer = this.currentPlayer === "player1" ? ".player2" : ".player1";
            const activePlayer = this.currentPlayer === "player1" ? ".player1" : ".player2";
            const nextIndex = this.feedIndex + 1; // calculate this early!

            // Move the inactive player down
            animate(inactivePlayer, {
                translateY: screenHeight,
                duration: 0
            });

            if (this.currentPlayer === "player1") {
                this.player2 = this.feed[nextIndex];
            } else {
                this.player1 = this.feed[nextIndex];
            }

            // animate players
            animate(activePlayer, {
                translateY: [0, -screenHeight],
                duration: 500,
                ease: createSpring({stiffness: this.stiffness, damping: this.damping})
            });

            animate(inactivePlayer, {
                translateY: [screenHeight, 0],
                duration: 500,
                ease: createSpring({stiffness: this.stiffness, damping: this.damping})
            }).then(() => {
                const nextPlayer = this.currentPlayer === "player1" ? "player2" : "player1";
                this.feedIndex = nextIndex;
                this.currentPlayer = nextPlayer;
				document.querySelector(activePlayer).querySelector(".video-container").querySelector("video").pause();
				document.querySelector(inactivePlayer).querySelector(".video-container").querySelector("video").play();

                this.animating = false;
            });
        },
        scrollUp() {
            if(this.animating) return;
            if (this.feedIndex <= 0) {
                console.log("Reached beginning of feed");
                this.animating = false;
                return;
            }

            this.animating = true;
            const screenHeight = window.innerHeight;
            const inactivePlayer = this.currentPlayer === "player1" ? ".player2" : ".player1";
            const activePlayer = this.currentPlayer === "player1" ? ".player1" : ".player2";
            const nextIndex = this.feedIndex - 1; // calculate this early!

            // Move the inactive player up
            animate(inactivePlayer, {
                translateY: -screenHeight,
                duration: 0
            });

            if (this.currentPlayer === "player1") {
                this.player2 = this.feed[nextIndex];
            } else {
                this.player1 = this.feed[nextIndex];
            }

            // animate players
            animate(activePlayer, {
                translateY: [0, screenHeight],
                duration: 500,
                ease: createSpring({stiffness: this.stiffness, damping: this.damping})
            });

            animate(inactivePlayer, {
                translateY: [-screenHeight, 0],
                duration: 500,
                ease: createSpring({stiffness: this.stiffness, damping: this.damping})
            }).then(() => {
                const nextPlayer = this.currentPlayer === "player1" ? "player2" : "player1";
                this.feedIndex = nextIndex;
                this.currentPlayer = nextPlayer;
				document.querySelector(activePlayer).querySelector(".video-container").querySelector("video").pause();
				document.querySelector(inactivePlayer).querySelector(".video-container").querySelector("video").play();

                this.animating = false;
            });
        },
        handleScroll(event) {
            if(this.animating) return;

            if(event.deltaY > 0) {
                this.scrollDown();
            } else {
                this.scrollUp();
            }
        },
		signedIn() {
			return Cookies.get('token') && Cookies.get('token').startsWith('HajeebToken')
		},
		handleTouch(event) {
			if(this.animating) return;
			this.touchInfo.push(event.touches[0].clientY);

			if ((this.touchInfo[this.touchInfo.length - 1] - this.touchInfo[0]) > 300) this.scrollUp();
			if ((this.touchInfo[0] - this.touchInfo[this.touchInfo.length - 1]) > 300) this.scrollDown();
		}
    },
    created () {
        // initial setup for players
        this.player1 = this.feed[this.feedIndex];
        this.player2 = this.feed[this.feedIndex + 1];

        document.addEventListener("wheel", this.handleScroll);
		document.addEventListener("touchmove", this.handleTouch);
		document.addEventListener("touchstart", (event) => {
			this.touchInfo = [];
			this.touchInfo.push(event.touches[0].clientY);
		});

		document.addEventListener("touchend", (event) => {
			this.touchInfo = [];
		});
    },
	mounted () {
		console.log("peepee")
		animate(".player2", {
			translateY: -window.innerHeight,
			duration: 0
		})
	},
    components: { Player },
})
</script>

<template>
    <div id="player-container">
        <Player
            class-name="player1"
            :video="player1?.id ?? 1"
            :key="player1?.id ?? 1"
            :information="{
                title: player1?.title ?? '',
                description: player1?.description ?? '',
                likes: player1?.likes ?? 13242,
                dislikes: player1?.dislikes ?? 13242,
                comments: player1?.comments ?? 13242,
                shares: player1?.shares ?? 13242,
                author: {
					username: player1?.author?.username ?? 'johnclapper',
					verified: player1?.author?.verified ?? false,
					id: player1?.author?.id ?? 1,
				}
            }"
        />

        <Player
            class-name="player2"
            :video="player2?.id ?? 1"
            :key="player2?.id ?? 1"
            :information="{
                title: player2?.title ?? '',
                description: player2?.description ?? '',
                likes: player2?.likes ?? 13242,
                dislikes: player2?.dislikes ?? 13242,
                comments: player2?.comments ?? 13242,
                shares: player2?.shares ?? 13242,
                author: {
					username: player2?.author?.username ?? 'johnclapper',
					verified: player2?.author?.verified ?? false,
					id: player2?.author?.id ?? 1,
				}
            }"
        />
    </div>
</template>

<style scoped>
#player-container
{
	flex-grow: 1;
	display: flex;
	justify-content: center;
}

.player1 {
    position: absolute;
}

.player2 {
    position: absolute;
}
</style>
