var ACC_X = 0;

var DEFAULT_X_INCLINATION = 0;
var xMax = 50;

var globalCoords = {};
globalCoords.leftAngle = 45;
globalCoords.rightAngle = -45;

//Initialize function
var init = function() {

    // SET THE SCREEN NOT TO FADE AFTER TIME --> remember to set the POWER privilege in the config.xml file first
    if (window.tizen) {
        tizen.power.request("SCREEN", "SCREEN_NORMAL");
    }

    //  ******** READ THE ACCELEROMETER X AXIS ********
    if (window.DeviceMotionEvent) {
        window.addEventListener("devicemotion", motion, false);
    } else {
        console.log("DeviceMotionEvent is not supported");
    }

    function motion(event) {
        //ACC_X = Math.round(xMax * ((event.accelerationIncludingGravity.x + DEFAULT_X_INCLINATION) / 90) * 100) / 90;
        ACC_X = Math.round(xMax * ((event.acceleration.x + DEFAULT_X_INCLINATION) / 90) * 100) / 90;
    }


    // ******** LOAD PLUGINS ********
    SceneJS.setConfigs({
        pluginPath: "./js/plugins"
    });

    // ******** CREATE THE SCENE ********
    var scene = SceneJS.createScene({
        nodes: [

            // ******** MOUSE CAMERA ********
            {
                type: "cameras/orbit",
                yaw: 180,
                pitch: -20,
                zoom: 11,
                zoomSensitivity: 1,

                nodes: [

                    // ******** LIGHTS ********

                    {
                        type: "lights",
                        id: "myLights",
                        lights: [{

                                mode: "point",
                                color: {
                                    r: 1.0,
                                    g: 1.0,
                                    b: 1.0
                                },
                                diffuse: true,
                                specular: true,
                                pos: {
                                    x: 10,
                                    y: 20,
                                    z: -20
                                },
                                constantAttenuation: 0.2, // [0..1]
                                linearAttenuation: 0, // [0..1]
                                quadraticAttenuation: 0, // [0..1]
                                space: "world"

                            },

                            {

                                mode: "point",
                                color: {
                                    r: 1.0,
                                    g: 1.0,
                                    b: 0.9
                                },
                                diffuse: true,
                                specular: true,
                                pos: {
                                    x: -20,
                                    y: 20,
                                    z: 7
                                },
                                constantAttenuation: 0.8, // [0..1]
                                linearAttenuation: 0, // [0..1]
                                quadraticAttenuation: 0, // [0..1]
                                space: "world"

                            }, {

                                mode: "point",
                                color: {
                                    r: 1.0,
                                    g: 1.0,
                                    b: 0.9
                                },
                                diffuse: true,
                                specular: true,
                                pos: {
                                    x: 10,
                                    y: 0,
                                    z: 20
                                },
                                constantAttenuation: 0, // [0..1]
                                linearAttenuation: 0, // [0..1]
                                quadraticAttenuation: 0, // [0..1]
                                space: "world"

                            }, {

                                mode: "point",
                                color: {
                                    r: 1.0,
                                    g: 1.0,
                                    b: 1
                                },
                                diffuse: true,
                                specular: true,
                                pos: {
                                    x: 0,
                                    y: -4,
                                    z: 4
                                },
                                constantAttenuation: 0.2, // [0..1]
                                linearAttenuation: 0, // [0..1]
                                quadraticAttenuation: 0, // [0..1]
                                space: "view"

                            }

                        ],



                        nodes: [

                            // ******** CREATE THE SKYBOX ********    

                            {
                                type: "skybox/lumberWorld",
                                size: 5000
                            }, {
                                type: "material",
                                color: {
                                    r: 0.4,
                                    g: 0.4,
                                    b: 0.9
                                },
                                nodes: [

                                    // Flags node which enables or disables pickability of the LumberJack
                                    {
                                        type: "flags",
                                        id: "myFlags",
                                        flags: {
                                            picking: true
                                        },

                                        nodes: [{

                                            type: "translate",
                                            id: "drwalTranslate",
                                            x: 0,
                                            y: -2.3,
                                            z: -0.2,

                                            nodes: [{

                                                type: "rotate",
                                                id: "LumberManWholeRotate",
                                                x: 1.0,
                                                angle: 90,

                                                nodes: [{

                                                    type: "rotate",
                                                    id: "LumberManWholeRotateZ",
                                                    z: 1.0,
                                                    angle: 180,

                                                    nodes: [{

                                                        type: "scale",
                                                        id: "myScale",
                                                        x: 0.0015,
                                                        y: 0.0015,
                                                        z: 0.0015,

                                                        nodes: [{

                                                            id: "lumberMaterial",
                                                            type: "material",
                                                            color: {
                                                                r: 1,
                                                                g: 1,
                                                                b: 1
                                                            },
                                                            specularColor: {
                                                                r: 1.0,
                                                                g: 1.0,
                                                                b: 1.0
                                                            },
                                                            specular: 1.0,
                                                            shine: 70.0,
                                                            emit: 0,
                                                            alpha: 1,

                                                            nodes: [{


                                                                type: "name",
                                                                name: "LumberMan",

                                                                nodes: [{

                                                                    type: "texture",
                                                                    src: "models/model_texture.jpg",

                                                                    nodes: [

                                                                        {
                                                                            type: "import/md2",
                                                                            src: "models/model_animated.md2",
                                                                            rate: 1
                                                                        }
                                                                    ]
                                                                }]
                                                            }]

                                                        }]

                                                    }]

                                                }]

                                            }]

                                        }]
                                    }

                                ]
                            }, {

                                type: "translate",
                                id: "cubeTranslate",
                                x: 0,
                                y: -2.3,
                                z: -0.2,

                                nodes: [{

                                    type: "rotate",
                                    id: "cubeRotate",
                                    x: 1,
                                    angle: 0,

                                    nodes: [{
                                        type: "texture",
                                        src: "models/cube_texture.jpg",

                                        nodes: [
                                            // Import Wavefront .OBJ mesh
                                            {
                                                type: "import/obj",
                                                src: "models/cube.obj"
                                            }
                                        ]
                                    }]
                                }]
                            }
                        ]
                    }
                ]
            }
        ]
    });

    // ****** TRANSLATE THE MOUSE CLICK INTO PICK *******

    var canvas = scene.getCanvas();

    canvas.addEventListener('mousedown', mouseDown, true);
    canvas.addEventListener('mouseup', mouseUp, true);
    canvas.addEventListener('touchstart', touchStart, true);
    canvas.addEventListener('touchend', touchEnd, true);

    var lastX;
    var lastY;
    var dragging;

    function mouseDown(event) {
        lastX = event.clientX;
        lastY = event.clientY;
        dragging = true;
    }

    function touchStart(event) {
        lastX = event.targetTouches[0].clientX;
        lastY = event.targetTouches[0].clientY;
        dragging = true;

    }

    function mouseUp(event) {
        if (dragging) {
            scene.pick(event.clientX, event.clientY);
        }
        dragging = false;
    }

    function touchEnd() {
        if (dragging) {
            try {
                scene.pick(event.targetTouches[0].clientX, event.targetTouches[0].clientY);
            } catch (err) {
                console.log("ERR = " + err);
            } finally {
                console.log("WEIRD PICKING STUFF!");
            }

            scene.getNode("lumberMaterial", function(lumberMaterial) {
                lumberMaterial.setColor({
                    r: 1,
                    g: 1,
                    b: 1
                });
            });
        }
        dragging = false;
    }

    // ******* HANDLE THE PICK EVENT FROM SCENE *******

    scene.on("pick",
        function(hit) {

            console.log("hit === " + hit);

            scene.getNode("lumberMaterial", function(lumberMaterial) {
                lumberMaterial.setColor({
                    r: 1,
                    g: 0,
                    b: 0
                });
            });


        });


    scene.getNode("myFlags", function(myFlags) {
        setInterval(
            function() {

                var enable = !myFlags.getPicking();

                myFlags.setPicking(enable);

            },
            3000);
    });



    // add eventListener for tizenhwkey
    document.addEventListener('tizenhwkey', function(e) {
        if (e.keyName == "back") {
            try {
                tizen.application.getCurrentApplication().exit();
            } catch (error) {
                console.error("getCurrentApplication(): " + error.message);
            }
        }
    });
};
// window.onload can work without <body onload="">
window.onload = init;