var scene_;
var rootNode;
var cameraNode_;
var rootUI;
var PIXEL_SIZE = 0.01;
var cursor_;
var event_;
var hero;
var heroInitX;
var heroInitY;
var starNumber = 0;
var assetsPath = "105_platform_jump/";
// 移动距离
var stepSize = 34;
var updateTime = new Date().getTime();
var startTime  = new Date().getTime();
var KEY_W = 119;
var KEY_S = 115;
var KEY_A = 97;
var KEY_D = 100;
var tip;
// 默认移动方向
var direction;
var score = 0;

// 游戏结束
var gameOver = false;
// 结束窗口
var window_ = -1;
/**
 * 开�
 */
function start()
{
    // 文件资源缓存
    var cache_ = game.getResourceCache();
    // 默认样式
    var style = cache_.getResourceXMLFile("UI/DefaultStyle.xml");
    // ui布局
    var ui_ = game.getUI();
    // ui根节点，类型：UIElement
    rootUI = ui_.getRoot();
    // ui根节点设置默认样�
    rootUI.setDefaultStyle(style);

    //
    ui_.getRoot().setDefaultStyle(style);

    event_ = event.create();
    createScene();
    setWindowTitleAndIcon();
    addBg();
    setupViewport();


    // Create a Cursor UI element because we want to be able to hide and show it at will. When hidden, the mouse cursor will
    // control the camera, and when visible, it will interact with the UI
    cursor_ = cursor.create();
    cursor_.setStyleAuto();
    // Set starting position of the cursor at the rendering window center
    var graphics_ = game.getGraphics();
    var width = graphics_.getWidth();
    var height = graphics_.getHeight();
    cursor_.setPosition(width / 2, height / 2);
    game.getUI().setCursor(cursor_);
    cursor_.setBringToFront(true);
    cursor_.bringToFront();

    init();

    event.bindEvent('E_UPDATE', 'handleUpdate');
    event_.bindEvent('E_KEYDOWN','handleKeyDown',this);

    // 物理结束接触事件
    event_.bindEvent('E_PHYSICSENDCONTACT2D', 'handlePhysics2DEvent', this);
}

// 初始化游戏场�
function init(){
    rootNode = scene_.createChild("root");
    scene_.addChild(rootNode);
    score = 0;
    starNumber = 0;
    tip.setText(score);
    gameOver = false;
    // 创建地面
    createPlatform(0,-3.7,10);
    createPlatform(-4,-2);
    createPlatform(0,-1);
    createPlatform(2,0,0.8);
    createPlatform(3.5,1);
    createPlatform(-4,2,1.8);

    createHero();

    for (var i = 0; i < 10; i++) {
        createStar(math.random(-4,4),4);
    }
}

this.handlePhysics2DEvent = function(eventData){
    if(eventData && !gameOver){
        var a = eventData.P_NODEA;
        var b = eventData.P_NODEB;
        var name = a.getName();
        var name2 = b.getName();
        // 触碰星星
        if ((name == "hero" && name2 == "star") || (name == "star" && name2 == "hero")){
            if(name == "star"){
                a.remove();
            }
            if(name2 == "star"){
                b.remove();
            }
            score++;
            starNumber = starNumber - 1;
            if(starNumber == 0){
                createStar(math.random(-4,4),4);
            }
            createBomb(math.random(-4,4),0);
        }
        // 触碰炸弹
        if ((name == "hero" && name2 == "bomb") || (name == "bomb" && name2 == "hero")){
            if(name == "bomb"){
                a.remove();
            }
            if(name2 == "bomb"){
                b.remove();
            }
            gameOver = true;
        }
        tip.setText("score:"+score);
        if(gameOver){
            gameEndLogic();
            return;
        }
    }
}

this.handleKeyDown = function (data)
{
    var key = data.P_KEY;

    // Close console (if open) or exit when ESC is pressed
    if (key == 27)//esc
    {
        game.exit();
    }
    if (key == KEY_W && direction != "down"){
        direction = "up";
    }
    if (key == KEY_S && direction != "up"){
        direction =  "down";
    }
    if (key == KEY_A && direction != "right"){
        direction =  "left";
    }
    if (key == KEY_D && direction != "left"){
        direction =  "right";
    }
    changeHeroPng();
    if(!gameOver){
        var st = new Date().getTime() - updateTime;
        if(st >= 10){
            changePosition(hero);
            updateTime = new Date().getTime();
        }
    }
}

function changeHeroPng(){
    var cache_ = game.getResourceCache();

    if(direction == "left"){
        hero.getComponentStaticSprite2D().setSprite(cache_.getResourceSprite2D(assetsPath+"dude_3.png"));
    }
    if(direction == "right"){
        hero.getComponentStaticSprite2D().setSprite(cache_.getResourceSprite2D(assetsPath+"dude_7.png"));
    }
    if(direction != "left" && direction != "right"){
        hero.getComponentStaticSprite2D().setSprite(cache_.getResourceSprite2D(assetsPath+"dude_5.png"));
    }
}

// 创建英雄
function createHero(){
    var graphics_ = game.getGraphics();
    var width = graphics_.getWidth();
    var height = graphics_.getHeight();

    var root = game.getUI().getRoot();
    var cache_ = game.getResourceCache();

    hero = rootNode.createChild("hero");
    hero.setName("hero");
    // 添加精灵组件
    var sprite2D = hero.createComponentStaticSprite2D();
    var img = cache_.getResourceSprite2D(assetsPath+"dude_5.png");
    // 使用源图像完全替换目标图像。不进行任何混合运算
    sprite2D.setBlendMode("BLEND_REPLACE");
    sprite2D.setSprite(img);

    // 添加物理刚体组件
    var body = hero.createComponentRigidBody2D();
    // 设置刚体类型为动�
    body.setBodyType('BT_DYNAMIC');
    // 质量
    body.setMass(5);
    body.setAllowSleep(false);
    // 设置碰撞检测模式（连续碰撞检测）
    // body.setBullet(true);
    // 限制速度
    body.setLinearVelocity(math.vector2(0, 0));
    // 禁用旋转
    body.setFixedRotation(true);


    // 创建一个矩形碰撞体
    var box = hero.createComponentCollisionBox2D();
    // 设置碰撞体大�
    box.setSize(math.vector2(0.5, 0.5));
    // 设置密度
    box.setDensity(1.0);
    // 设置摩擦�
    box.setFriction(0.5);
    // 设置恢复系数（弹性）
    box.setRestitution(0.1);

    hero.setPosition(math.vector3(0, 0,0));
    hero.setScale(math.vector3(1.0, 1.0, 0.0));

    return hero;
}
// 创建星星
function createStar(x,y){
    var graphics_ = game.getGraphics();
    var width = graphics_.getWidth();
    var height = graphics_.getHeight();

    var root = game.getUI().getRoot();
    var cache_ = game.getResourceCache();

    var star = rootNode.createChild("star");
    star.setName("star");
    // 添加精灵组件
    var sprite2D = star.createComponentStaticSprite2D();
    var img = cache_.getResourceSprite2D(assetsPath+"star.png");
    // 使用源图像完全替换目标图像。不进行任何混合运算
    sprite2D.setBlendMode("BLEND_ALPHA");
    sprite2D.setSprite(img);

    // 添加物理刚体组件
    var body = star.createComponentRigidBody2D();
    // 设置刚体类型为动�
    body.setBodyType('BT_DYNAMIC');
    // 质量
    body.setMass(1);
    body.setAllowSleep(false);
    // 设置碰撞检测模式（连续碰撞检测）
    body.setBullet(true);
    // 限制速度
    body.setLinearVelocity(math.vector2(0, 0));
    // 禁用旋转
    body.setFixedRotation(true);

    // 创建一个矩形碰撞体
    var box = star.createComponentCollisionBox2D();
    // 设置碰撞体大�
    box.setSize(math.vector2(0.1, 0.2));
    // 设置密度
    box.setDensity(1.0);
    // 设置摩擦�
    box.setFriction(0.5);
    // 设置恢复系数（弹性）
    box.setRestitution(math.random(0.9));

    star.setPosition(math.vector3(x,y,0));
    star.setScale(math.vector3(1.0, 1.0, 0.0));
    starNumber = starNumber + 1;
    return star;
}
// 创建炸弹
function createBomb(x,y){
    var graphics_ = game.getGraphics();
    var width = graphics_.getWidth();
    var height = graphics_.getHeight();

    var root = game.getUI().getRoot();
    var cache_ = game.getResourceCache();

    var bomb = rootNode.createChild("bomb");
    bomb.setName("bomb");
    // 添加精灵组件
    var sprite2D = bomb.createComponentStaticSprite2D();
    var img = cache_.getResourceSprite2D(assetsPath+"bomb.png");
    // 使用源图像完全替换目标图像。不进行任何混合运算
    sprite2D.setBlendMode("BLEND_ALPHA");
    sprite2D.setSprite(img);

    // 添加物理刚体组件
    var body = bomb.createComponentRigidBody2D();
    // 设置刚体类型为动�
    body.setBodyType('BT_DYNAMIC');
    // 质量
    body.setMass(1);
    body.setAllowSleep(false);
    // 设置碰撞检测模式（连续碰撞检测）
    body.setBullet(true);
    // 限制速度
    body.setLinearVelocity(math.vector2(0, 0));
    // 禁用旋转
    body.setFixedRotation(true);

    // 创建一个矩形碰撞体
    var box = bomb.createComponentCollisionBox2D();
    // 设置碰撞体大�
    box.setSize(math.vector2(0.1, 0.2));
    // 设置密度
    box.setDensity(1.0);
    // 设置摩擦�
    box.setFriction(0.1);
    // 设置恢复系数（弹性）
    box.setRestitution(1);

    bomb.setPosition(math.vector3(x,y,0));
    bomb.setScale(math.vector3(1.0, 1.0, 0.0));

    return bomb;
}
// 创建地面平台
function createPlatform(x, y,widthScale){
    var graphics_ = game.getGraphics();
    var width = graphics_.getWidth();
    var height = graphics_.getHeight();

    var root = game.getUI().getRoot();
    var cache_ = game.getResourceCache();

    var platform = rootNode.createChild("platform"+x+y);

    // 添加精灵组件
    var sprite2D = platform.createComponentStaticSprite2D();
    var img = cache_.getResourceSprite2D(assetsPath+"platform.png");
    // 使用源图像完全替换目标图像。不进行任何混合运算
    sprite2D.setBlendMode("BLEND_REPLACE");
    sprite2D.setSprite(img);

    // 为地面创�D刚体
    var rigidBody2D = platform.createComponentRigidBody2D();
    // 设置刚体类型为静�
    rigidBody2D.setBodyType('BT_STATIC');
    // 设置碰撞检测模式（连续碰撞检测）
    rigidBody2D.setBullet(true);

    platform.setPosition(math.vector3(x,y));
    if(widthScale){
        // 设置大小
        platform.setScale(math.vector3(widthScale, 1.0, 0.0));
    }else {
        platform.setScale(math.vector3(1.0, 1.0, 0.0));
    }

    // 创建一个矩形碰撞体
    var groundShape = platform.createComponentCollisionBox2D();
    // 设置碰撞体大�
    groundShape.setSize(3.6,0.3);
    // 设置密度
    groundShape.setDensity(1.0);
    // 设置摩擦�
    groundShape.setFriction(0.6);

    return platform;
}

function handleUpdate(eventData)
{


}

function changePosition(node){
    var graphics_ = game.getGraphics();
    var w = graphics_.getWidth();
    var h = graphics_.getHeight();
    var position = node.getPosition();

    var x = math.getX(position);
    var y = math.getY(position);
    if(direction && node){
        var body2D = node.getComponentRigidBody2D();

        var moveDir;
        if(direction == "left"){
            moveDir  = math.vector2(-2, 0);
        }
        if(direction == "right"){
            moveDir  = math.vector2(2, 0);
        }
        if(direction == "up"){
            moveDir  = math.vector2(0, 5);
            // body2D.applyAngularImpulse(0.3,true);
        }
        if(direction == "down"){
        }
        if(!gameOver && moveDir){
            body2D.setLinearVelocity(moveDir);
            // node.setPosition(newPos);
        }
        body2D.setAwake(true);
        direction = 0;
    }
}

function gameEndLogic() {
    if(gameOver) {
        initWindow();
        initControls();
        if (window_) {
            var timeText = window_.getChild("timeText", true);
            if (timeText) {
                var endTime = new Date().getTime();
                var seconds = (endTime - startTime) / 1000;
                timeText.setText("seconds:" + seconds);
            }
            var scoreText = window_.getChild("scoreText", true);
            if (scoreText) {
                scoreText.setText("score:" + score);
            }
        }
    }
}

function initWindow()
{
    if(window_ != -1){
        window_.remove();
    }
    // Create the Window and add it to the UI's root node
    window_ = window.create();
    rootUI.addChild(window_);

    // Set Window size and layout settings
    window_.setMinWidth(384);
    window_.setLayout('LM_VERTICAL', 6, math.intRect(6, 6, 6, 6));
    window_.setAlignment('HA_CENTER', 'VA_CENTER');
    window_.setName("Window");
    // colorBLACK()
    window_.setModalShadeColor(math.colorWHITE())
    window_.setModalFrameColor(math.colorWHITE())
    window_.setColor(math.colorWHITE())
    window_.bringToFront(true)

    // Create Window 'titlebar' container
    var titleBar =  uielement.create();
    titleBar.setMinSize(0, 24);
    titleBar.setVerticalAlignment('VA_TOP');
    titleBar.setLayoutMode('LM_HORIZONTAL');

    // Create the Window title Text
    var windowTitle = text.create();
    windowTitle.setName("WindowTitle");
    windowTitle.setText("game over!");
    // windowTitle.SetText("Hello GUI!");

    // Create the Window's close button
    var buttonClose = button.create();
    buttonClose.setName("CloseButton");


    // Add the controls to the title bar
    titleBar.addChild(windowTitle);
    titleBar.addChild(buttonClose);

    // Add the title bar to the Window
    window_.addChild(titleBar);

    // Apply styles
    var b= window_.setStyleAuto();

    windowTitle.setStyleAuto();
    buttonClose.setStyle("CloseButton");
    event_.bindEvent(buttonClose, 'E_RELEASED', 'handleClosePressed');
}

function initControls()
{
    var cache_ = game.getResourceCache();
    // 字体
    var font_ = cache_.getResourceFont("Fonts/Anonymous Pro.ttf");
    // Create a CheckBox


    // Create a Button
    var restartButton = button.create();
    restartButton.setName("Button");
    restartButton.setMinHeight(24);
    restartButton.setMaxWidth(100);
    var buttonText = restartButton.createChildText();
    // 设置水平和垂直对�
    buttonText.setAlignment('HA_CENTER', 'VA_CENTER');
    buttonText.setFont(font_, 17);
    buttonText.setColor(math.color(0.0, 0.0, 0.0));
    buttonText.setText("Restart");

    var exitButton = button.create();
    exitButton.setName("Button");
    exitButton.setMinHeight(24);
    exitButton.setMaxWidth(100);
    var buttonText2 = exitButton.createChildText();
    // 设置水平和垂直对�
    buttonText2.setAlignment('HA_CENTER', 'VA_CENTER');
    buttonText2.setFont(font_, 17);
    buttonText2.setColor(math.color(0.0, 0.0, 0.0));
    buttonText2.setText("Exit");


    var timeText = text.create();
    timeText.setName("timeText");
    timeText.setColor(math.colorWHITE());

    var scoreText = text.create();
    scoreText.setName("scoreText");
    scoreText.setColor(math.colorWHITE())

    // Add controls to Window
    window_.addChild(scoreText);
    window_.addChild(timeText);
    window_.addChild(restartButton);
    window_.addChild(exitButton);

    // Apply previously set default style
    restartButton.setStyleAuto();
    exitButton.setStyleAuto();
    timeText.setStyleAuto();
    scoreText.setStyleAuto();
    // 绑定点击事件restartclick
    event.create().bindEvent(restartButton,"E_CLICK",'restartButtonClick',this);
    event.create().bindEvent(exitButton,"E_CLICK",'exitButtonClick',this);
}

function handleClosePressed(){
    if(window_ != -1){
        window_.remove();
        window_ = -1;
    }
}

/**
 * 重新开�
 */
function restartButtonClick()
{
    if(window_ != -1){
        window_.remove();
        window_ = -1;
    }

    startTime = new Date().getTime();
    updateTime = new Date().getTime();

    // scene_.removeAllChildren();

    scene_.removeChild(rootNode);
    init();
}


function exitButtonClick(){
    game.exit()
}

/**
 * 游戏窗口：标题，图标
 */
function setWindowTitleAndIcon()
{
    // 游戏窗口
    var graphics_ = game.getGraphics();
    // 文件资源缓存
    var cache_ = game.getResourceCache();
    // 窗体图标
    // var icon = cache_.getResourceImage("Textures/saolei/btlei.png");
    //
    // graphics_.setWindowIcon(icon);
    // 窗体标题
    graphics_.setWindowTitle("platform jump");
}


// 设置视口
function setupViewport()
{
    var renderer_ = game.getRenderer();
    var viewport_=viewport.create(scene_, cameraNode_.getComponentCamera());
    renderer_.setViewport(0, viewport_);
}

/**
 * 创建场景
 */
function createScene()
{
    if(!scene_){
        // 场景对象
        scene_ = scene.create();
    }

    // Octree
    scene_.createComponentOctree();

    var debugRenderer = scene_.createComponentDebugRenderer();
    // 获取物理世界
    var physicsWorld = scene_.createComponentPhysicsWorld2D();
    physicsWorld.setDrawJoint(true);
    // 设置重力向量（例如，从上向下的重力）
    physicsWorld.setGravity(math.vector2(0.0, -9.8));
    physicsWorld.setEnabled(true);
    physicsWorld.drawDebugGeometry(debugRenderer,true);

    // 创建子场景节点：Camera
    cameraNode_ = scene_.createChild("Camera");
    // 位置
    cameraNode_.setPosition(math.vector3(0.0, 0.0, -10.0));

    // 子节点创建Camera类并返回�
    var camera_ = cameraNode_.createComponentCamera();
    // 正交模式
    camera_.setOrthographic(true);

    var graphics_ = game.getGraphics();
    // 设置正交模式视图非均匀大小。禁用自动长宽比模式�
    camera_.setOrthoSize(graphics_.getHeight() * PIXEL_SIZE);
}

/**
 * 添加背景
 */
function addBg()
{
    var graphics_ = game.getGraphics();
    // 窗口宽度 (以像素为单位)
    var width = graphics_.getWidth();
    // 窗口高度 (以像素为单位)
    var height = graphics_.getHeight();

    var cache_ = game.getResourceCache();
    //  UI 元素
    var  sprite_ = sprite.create();
    // var cache_ = game.getResourceCache();
    // 背景图片
    var decalTex = cache_.getResourceTexture2D(assetsPath+"mainbg.png");
    // 设置背景图片纹理
    sprite_.setTexture(decalTex);
    // 位置
    sprite_.setPosition(math.vector2(0,0));
    // 大小
    sprite_.setSize(math.intVector2(width, height));
    // 设置混合模式
    sprite_.setBlendMode('BLEND_ADD');
    // 添加到根节点
    rootUI.addChild(sprite_);

    // 字体
    var font_ = cache_.getResourceFont("Fonts/Anonymous Pro.ttf");

    // 文本ui元素
    tip = text.create();
    // textbs.setAlignment('HA_CENTER', 'VA_CENTER');
    // 字体和大�
    tip.setFont(font_, 15);
    // 颜色
    tip.setColor(math.color(1.0, 0.0, 0.0));
    // 设置文本
    tip.setText("default");
    // 位置
    tip.setPosition(width-100,20);
    sprite_.addChild(tip);
}

game.init();

start();

game.run();
