define(["three", "resources", "skySphere", "meshTree", "util", "camera", "objects", "random"],
    function(THREE, resources, skySphere, MeshTree, Util, camera, objects, Random) {
        var scene = new THREE.Scene();

        var hat, material;

        var meshTree;

        var light, hemiLight;

        var sceneTime = 0;

        var seeds = [294, 504, 38205, 2598];
        var meshTrees = [];
        var iTree = 0;        

        scene.init = function() {
            light = new THREE.SpotLight(0xFFFFFF, .504);
            light.position.set(0, 30, 0);
            this.fastMode = false;

            hemiLight = new THREE.HemisphereLight(0xFFFFFF, 0x666666, 0.5);

            for(var i in seeds)
            {
                var mt = new MeshTree();
                var branch = mt.rootBranch;
                branch.random = new Random(seeds[i]);
                branch.position.setY(-20);
                branch.mesh = objects.hat.clone();
                branch.generate();
                branch.meshes[0].rotation.set(0, 0, Math.PI);
                branch.recurse();

                meshTrees.push(mt);
            }

            meshTree = meshTrees[0];

            scene.add(meshTree.rootBranch);
            scene.add(hemiLight);
            scene.add(skySphere.clone());
            scene.add(light);
        }

        scene.enter = function() {
            camera.reset();
            if(!this.fastMode)
            {
                camera.position.z = 80;
                camera.position.y = -80;
            }
            else
            {
                camera.position.z = 80;
                camera.position.y = -20;
            }
            sceneTime = 0;
        }

        var switchMeshTree = function(tree) {
            scene.remove(meshTree.rootBranch);
            camera.position.z = 80;
            camera.position.y = -20;
            meshTree = tree;
            scene.add(meshTree.rootBranch);
        }

        scene.update = function(t, dt) {
            sceneTime += dt;
            meshTree.rootBranch.rotation.y += dt;

            var beatTime = Util.beatsToTime(130, {
                bars: 4
            });
            
            if(camera.position.y < 5)
            {
                camera.position.y += 10 * dt;
            }

            if(sceneTime > beatTime) {
                if(++iTree >= meshTrees.length)
                    iTree = 0;
                switchMeshTree(meshTrees[iTree]);
                sceneTime = 0;
            }

            meshTree.setGrowth(sceneTime / beatTime);
            this.fadeAmount = (1.0 - (sceneTime * 2)).clamp(0, 1);
        }

        return scene;
    });
