/*
 * Copyright (c) 2017 kawtu
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

var c_maxscenes = 10;
var c_variants = ['-in', ''];
var c_maxsegments = c_maxscenes * c_variants.length;

var g_videos = [];
var g_cvideoel;
var g_dir = 0;
var g_fwd;
var g_bck;

function initKeys() {
    document.addEventListener('keyup', function (ev) {

    });
}

function initButtons() {
    g_fwd = document.getElementById('forwards');
    g_bck = document.getElementById('backwards');

    g_fwd.addEventListener('click', function() {
        g_dir = 1;
        this.style.opacity = 1.0;
        g_cvideoel.loop = false;
    });
    g_bck.addEventListener('click', function() {
        g_dir = -1;
        this.style.opacity = 1.0;
        g_cvideoel.loop = false;
    });
}

function isAllReady() {
    var ready = true;
    for(vi in g_videos) {
        var vo = g_videos[vi];
        ready = ready && (vo.stat == 'ready' || vo.stat == 'errored');
    }

    return ready;
}

function kickoff() {
    console.log('kickoff');

    var i=0;
    for(i in g_videos) {
        if(g_videos[i].stat == 'ready')
            break;
    }

    g_cvideoel = g_videos[i].el;
    g_cvideoel.style.display = 'block';
    g_cvideoel.style.zIndex = 0;
    g_cvideoel.play();
}

function initVideo (vo) {
    console.log('init video', vo);
    var el = document.createElement('video');
    el.id = vo.id;
    el.src = vo.src;
    //el.controls = true;
    if(vo.loop)
        el.loop = true;

    el.addEventListener('error', function(){
        console.log(vo.id + ' errored');
        vo.stat = 'errored';
        this.remove();
    });

    function canplaythrough(){
        el.removeEventListener('canplaythrough', canplaythrough);

        console.log(vo.id + ' canplaythrough');
        vo.stat = 'ready';
        if(isAllReady()) {
            kickoff();
        }
    }

    function ended() {
        console.log(vo.id + ' ended, dir=', g_dir);

        if(g_dir == 0 && !el.loop) {
            console.log('not looping', vo, vo.next());
            g_dir = 1;
        }

        if(g_dir != 0) {
            if(g_dir == 1 && vo.next().stat == 'ready') {
                g_cvideoel = vo.next().el;
                g_cvideoel.play();
                g_cvideoel.style.display = 'block';
                g_cvideoel.style.zIndex = 0;
            } else if(g_dir == -1 && vo.prev().stat == 'ready') {
                g_cvideoel = vo.prev().el;
                g_cvideoel.style.display = 'block';
                g_cvideoel.style.zIndex = 0;
                g_cvideoel.play();
            }

            if(g_cvideoel != el) {
                el.removeAttribute("style");
                el.pause();
                el.load();
                el.loop = vo.loop;
            }
        }

        g_fwd.removeAttribute("style");
        g_bck.removeAttribute("style");
        g_dir = 0;
    }

    el.addEventListener('canplaythrough', canplaythrough);
    el.addEventListener('ended', ended);

    return el;
}

function initVideos() {
    var j = 0;
    for(var i=0; i < c_maxscenes; i++) {
        for(vi in c_variants) {
            (function (j, vo){
                vo.variant = c_variants[vi];
                vo.loop = vo.variant == '';
                vo.src = 'data/' + i + vo.variant + '.mp4';
                vo.id = vo.src;
                vo.stat = 'init';
                vo.next = function next() {
                    var k=j;
                    for(; k++, k < c_maxsegments;) {
                        if(g_videos[k].stat == 'ready')
                            break;
                    }
                    if(g_videos[k])
                        return g_videos[k];
                    else
                        return vo
                };
                vo.prev = function prev() {
                    var k=j;
                    for(; k--, k > 0;) {
                        if(g_videos[k].stat == 'ready')
                            break;
                    }
                    if(g_videos[k])
                        return g_videos[k];
                    else
                        return vo
                };

                vo.el   = initVideo(vo)
                document.body.appendChild(vo.el);

                console.log(vo.el)
            })(j, g_videos[j++] = {});
        }
    }
}

function init() {
    initButtons();
    initVideos();
}

window.addEventListener('load', function(){
    init();
})
