// source --> https://driving-test-success.com/wp-content/plugins/dtt-app/assets/js/app.js?ver=6.9.4 
(function ($) {
    // Custom code here
    $(function () {
        function timeStringToSeconds(str) {
            var parts = str.split(":").map(Number);
            if (parts.length === 3) {
                return parts[0] * 3600 + parts[1] * 60 + parts[2];
            }

            if (parts.length === 2) {
                return parts[0] * 60 + parts[1];
            }

            return parseFloat(str);
        }

        $(".js-dtt-video-player").each(function () {
            var $this = $(this);
            var videos = $this.data("videos");
            var minScore = $this.data("minScore");
            var clicks = {};

            if (!videos) {
                videos = [];
            }

            videos.forEach(function (video) {
                clicks[video["id"]] = [];
            });

            var mainVideo =
                videos.length > 0
                    ? videos[0]
                    : {
                          extension: "",
                          label: "",
                          timeframes: [],
                          video: "",
                      };

            // console.log(clicks);
            
            new Vue({
                el: this,
                data: {
                    videos: videos,
                    mainVideo: mainVideo,
                    // mainVideoLength: mainVideo.length ? mainVideo.length : 0,
                    showStartOverlay: true,
                    isTestEnded: false,
                    isTestReplaying: false,
                    currentVideoId: mainVideo["id"],
                    clicks: Object.assign({}, clicks),
                    minScore: minScore,
                },

                computed: {
                    maxClicksPerVideo: function() {
                        return 9;
                    },
                    // mainVideoLength: function() {
                    //     console.log(this.$refs.video);
                    //     return this.$refs.video ? Number(this.$refs.video.duration.toFixed(2)) : 0;
                    //     return this.mainVideo.length;
                    // },
                    currentVideoClicks: function () {
                        return this.clicks[this.currentVideoId];
                    },

                    hasPassed: function () {
                        return this.minScore <= this.calcPointsForTest();
                    },
                },

                mounted: function () {
                    MicroModal.init({
                        'onClose': function(modal) {
                            // console.log(this.$refs.video, modal.id);
                            this.$refs.video.play();
                        }.bind(this)
                    });
                    // this.$refs.video.addEventListener('loadedmetadata', function() {
                    //     console.log("Video duration: " + this.$refs.video.duration + " seconds");
                    //     this.mainVideoLength = Number(this.$refs.video.duration.toFixed(2));
                    // }.bind(this));
                },
                methods: {
                    getStyleForTimeframeScore: function(timeframe) {
                        var start = timeStringToSeconds(timeframe.start);
                        var end = timeStringToSeconds(timeframe.end);
                        // var timeframeDuration = end - start;
                        var videoDuration = this.mainVideo.length;
                        // var videoDuration = this.$refs.video ? this.$refs.video.duration : 1;

                        var left = (start / videoDuration) * 100 + '%';
                        var width = ((end - start) / videoDuration) * 100 + '%';

                        // console.log(left, width, timeframe);

                        return {
                            left: left,
                            width: width
                        };
                    },

                    showProgress: function () {
                        var lastTime = 0;
                        var video = this.$refs.video;

                        video.addEventListener("timeupdate", function() {
                            if (! video.seeking) {
                                var percent = (video.currentTime / video.duration) * 100;
                                this.$refs.progressBar.style.width = percent + "%";
                                this.$refs.progressCursor.style.left = percent + "%";
                                lastTime = video.currentTime;
                            }
                        }.bind(this));
                    },
                    endTest: function () {
                        this.isTestEnded = true;
                        this.$refs.video.pause();
                    },
                    onVideoEnded: function () {
                        var currentVideoIndex = this.videos.indexOf(this.mainVideo);
                        if (
                            currentVideoIndex == -1 ||
                            currentVideoIndex == this.videos.length - 1
                        ) {
                            // console.log(
                            //     "Last Video. Final score: " +
                            //         this.calcPointsForTest()
                            // );

                            this.endTest();
                            return;
                        }

                        var nextMainVideoIndex = currentVideoIndex + 1;
                        var newMainVideo = this.videos[nextMainVideoIndex];

                        this.setMainVideo(newMainVideo);
                        this.playVideo(0);
                    },
                    setMainVideo: function (video) {
                        this.mainVideo = video;
                        this.currentVideoId = video["id"];
                    },
                    onOverlayClick: function () {
                        this.playVideo(0);
                    },

                    onPlaylistVideoClick: function (video) {
                        return;

                        if (video["id"] == this.currentVideoId) {
                            return false;
                        }

                        this.setMainVideo(video);
                        this.playVideo(0);
                    },

                    playVideo: function (currentTime) {
                        var video = this.$refs.video;
                        video.pause();
                        video.currentTime = currentTime;
                        video.load();
                        video.play();

                        this.showStartOverlay = false;

                        this.showProgress();
                    },

                    checkIfVideoIsPlaying: function () {
                        var video = this.$refs.video;

                        return (
                            video &&
                            !!(
                                video.currentTime > 0 &&
                                !video.paused &&
                                !video.ended &&
                                video.readyState > 2
                            )
                        );
                    },

                    onVideoClick: function () {
                        if (this.isTestReplaying) {
                            return;
                        }
                        
                        var video = this.$refs.video;
                        var currentTime = video.currentTime;
                        // console.log(`Video clicked at ${currentTime.toFixed(2)} seconds`);

                        this.currentVideoClicks.push(currentTime.toFixed(2));

                        // When you've just exceeded max clicks show error message.
                        if (this.currentVideoClicks.length == this.maxClicksPerVideo + 1) {
                            MicroModal.show('hazard-test-modal', {
                                'onClose': function(modal) {
                                    // console.log(this.$refs.video, modal.id);
                                    this.$refs.video.play();
                                }.bind(this)
                            });

                            this.$refs.video.pause();
                            return;
                        }

                        // console.log(
                        //     this.calcPointsForTest(),
                        //     this.calcPointsForVideo(this.currentVideoId)
                        // );
                    },

                    calcPointsForVideo: function (videoId) {
                        var video = this.videos.find((v) => v.id === videoId);
                        if (!video) {
                            return 0;
                        }

                        var clickTimes = this.clicks[videoId] || [];

                        if (clickTimes.length > this.maxClicksPerVideo) {
                            return 0;
                        }

                        var totalPoints = 0;

                        for (var tf of video.timeframes) {
                            var start = timeStringToSeconds(tf.start);
                            var end = timeStringToSeconds(tf.end);
                            var duration = end - start;
                            var segment = duration / 5;

                            var bestPoints = 0;

                            for (var click of clickTimes) {
                                if (click >= start && click <= end) {
                                    var offset = click - start;
                                    let points = 5 - Math.floor(offset / segment);

                                    if (points < 1) {
                                        points = 1;
                                    }

                                    if (points > bestPoints) {
                                        bestPoints = points;
                                    }
                                }
                            }

                            totalPoints += bestPoints;
                        }

                        return totalPoints;
                    },

                    calcPointsForTest() {
                        var total = 0;

                        for (var video of this.videos) {
                            total += this.calcPointsForVideo(video.id);
                        }

                        return total;
                    },

                    restartTest: function () {
                        // this.clicks = clicks;
                        // console.log(clicks);
                        this.isTestEnded = false;
                        this.isTestReplaying = false;
                        this.showStartOverlay = true;

                        this.setMainVideo(this.videos[0]);

                        Object.keys(this.clicks).forEach(function(key) {
                            this.clicks[key] = [];
                        }.bind(this));
                        // this.playVideo(0);
                    },

                    replayTest: function () {
                        // this.clicks = clicks;
                        this.isTestEnded = false;
                        this.isTestReplaying = true;
                        // this.showStartOverlay = true;

                        this.setMainVideo(this.videos[0]);
                        this.playVideo(0);
                    },

                    getFlagMargin: function (clickTime) {
                        // console.log(this.$refs.video);
                        // var totalVideoLength = this.$refs.video.duration;
                        // var totalVideoLength = this.$refs.video ? this.$refs.video.duration : 1;
                        var totalVideoLength = this.mainVideo.length;
                        
                        var marginLeft = (clickTime / totalVideoLength).toFixed(2);

                        // console.log(clickTime, marginLeft);

                        return marginLeft * 100 + "%";
                    },
                },
            });
        });
    });
})(jQuery);