'use strict';

var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');

var CAMERA_POLLING_INTERVAL = 100;
var CAMERA_DELTA = 0.001;

var AppView = Backbone.View.extend({

    el: 'body',

    events: {
        'click .model-selection-a .needle-selector' : 'loadSelectionA',
        'click .model-selection-b .needle-selector' : 'loadSelectionB'
    },

    loadSelectionA: function(event){
        var selectedSketchfabid = event.currentTarget.getAttribute('data-sketchfabid');
        this.iframeA.setAttribute('data-active-sketchfabid', selectedSketchfabid);
        this.iframeA.setAttribute('data-active-needle-type', event.currentTarget.getAttribute('data-needle-type'));
        this.iframeA.setAttribute('data-active-needle-desc', event.currentTarget.getAttribute('data-original-title'));
        this.viewers.a.urlid = selectedSketchfabid;
        this.initViewerA();
        this.hideElement(this.legendA);
    },

    loadSelectionB: function(event){
        var selectedSketchfabid = event.currentTarget.getAttribute('data-sketchfabid');
        this.iframeB.setAttribute('data-active-sketchfabid', selectedSketchfabid);
        this.iframeB.setAttribute('data-active-needle-type', event.currentTarget.getAttribute('data-needle-type'));
        this.iframeB.setAttribute('data-active-needle-desc', event.currentTarget.getAttribute('data-original-title'));
        this.viewers.b.urlid = selectedSketchfabid;
        this.initViewerB();
        this.hideElement(this.legendB);
    },

    changeLegend: function(legend, needleType, needleDesc){
        $(legend).html('<h2>' + needleType + '</h2>' + '<p class="small">' + needleDesc.replace(/,/g, '<br>') + '</p> ').delay(2000).fadeIn('slow');
    },

    hideElement: function(targetEl){
        $(targetEl).fadeOut('slow');
    },

    initialize: function() {
        var version = '1.0.0';

        this.iframeA = this.$el.find('#viewer-a-frame').get(0);
        this.iframeB = this.$el.find('#viewer-b-frame').get(0);

        this.currentViewer = false;
        this.legendA = this.$el.find('#needle-a-legend').get(0);
        this.legendB = this.$el.find('#needle-b-legend').get(0);
        this.startscreenA = this.$el.find('#viewer-a-startscreen').get(0);
        this.startscreenB = this.$el.find('#viewer-b-startscreen').get(0);

        this.viewers = {
            'a': {
                _id: 'a',
                api: null,
                client: new Sketchfab(version, this.iframeA),
                ready: false,
                urlid: this.iframeA.getAttribute('data-active-sketchfabid'),
                camera: null,
                previousCamera: {
                    position: [0, 0, 0],
                    target: [0, 0, 0]
                }
            },
            'b': {
                _id: 'b',
                api: null,
                client: new Sketchfab(version, this.iframeB),
                ready: false,
                urlid: this.iframeB.getAttribute('data-active-sketchfabid'),
                camera: null,
                previousCamera: {
                    position: [0, 0, 0],
                    target: [0, 0, 0]
                }
            }
        };
        if ( this.iframeA.getAttribute('data-active-sketchfabid') != '' ) {
            this.initViewerA();
        }
        if ( this.iframeB.getAttribute('data-active-sketchfabid') != '' ) {
            this.initViewerB();
        }
    },

    initViewerA: function() {
        console.log('active sketchfabid A: ' + this.viewers.a.urlid);
        this.viewers.a.client.init(this.viewers.a.urlid, {
            camera: 0,
            success: function onSuccess(apiA) {
                console.log('Viewer A success');
                this.viewers.a.api = apiA;
                apiA.start();
                this.changeLegend(this.legendA, this.iframeA.getAttribute('data-active-needle-type'), this.iframeA.getAttribute('data-active-needle-desc'));
                this.hideElement(this.startscreenA);
                apiA.addEventListener('viewerready', function() {
                    this.viewers.a.ready = true;
                    this.onViewersReady();
                }.bind(this));
            }.bind(this),
            error: function onError() {
                console.log('Viewer A error');
            }
        });
    },

    initViewerB: function() {
        console.log('active sketchfabid B: ' + this.viewers.b.urlid);
        this.viewers.b.client.init(this.viewers.b.urlid, {
            camera: 0,
            success: function onSuccess(apiB) {
                console.log('Viewer B success');
                this.viewers.b.api = apiB;
                apiB.start();
                this.changeLegend(this.legendB, this.iframeB.getAttribute('data-active-needle-type'), this.iframeB.getAttribute('data-active-needle-desc'));
                this.hideElement(this.startscreenB);
                apiB.addEventListener('viewerready', function() {
                    this.viewers.b.ready = true;
                    this.onViewersReady();
                }.bind(this));
            }.bind(this),
            error: function onError() {
                console.log('Viewer B error');
            }
        });
    },

    onViewersReady: function() {

        var self = this;

        if (this.viewers.a.ready && this.viewers.b.ready) {

            this.startCameraPolling();

            this.viewers.a.api.setCameraLookAt([0, -10, 0], [0, 0, 0], 2);
            this.viewers.b.api.setCameraLookAt([0, -10, 0], [0, 0, 0], 2);
        }
    },

    startCameraPolling: function() {
        this._pollingTimer = setInterval(function() {
            this.viewers.a.api.getCameraLookAt(function(err, camera) {
                this.viewers.a.camera = camera;
                this._onCameraPolled(this.viewers.a);
            }.bind(this));
            this.viewers.b.api.getCameraLookAt(function(err, camera) {
                this.viewers.b.camera = camera;
                this._onCameraPolled(this.viewers.b);
            }.bind(this));
        }.bind(this), CAMERA_POLLING_INTERVAL);
    },

    _onCameraPolled: function(viewer) {
        var camera = viewer.camera;
        var previousCamera = viewer.previousCamera;

        var positionDistance = vec3.distance(
            vec3.fromValues(camera.position[0], camera.position[1], camera.position[2]),
            vec3.fromValues(previousCamera.position[0], previousCamera.position[1], previousCamera.position[2])
        );
        var targetDistance = vec3.distance(
            vec3.fromValues(camera.target[0], camera.target[1], camera.target[2]),
            vec3.fromValues(previousCamera.target[0], previousCamera.target[1], previousCamera.target[2])
        );

        viewer.previousCamera = camera;
        var totalDistance = positionDistance + targetDistance;
        if (totalDistance < CAMERA_DELTA) {
            if (this.currentViewer !== false) {
                this.currentViewer = false;
            }
        } else {
            if (this.currentViewer === false) {
                this.currentViewer = viewer._id;
            }

            if (this.currentViewer === 'a') {
                this.viewers.b.api.setCameraLookAt(camera.position, camera.target, 0.5);
            }
            if (this.currentViewer === 'b') {
                this.viewers.a.api.setCameraLookAt(camera.position, camera.target, 0.5);
            }
        }
    }

});

module.exports = AppView;
