import QtQuick 1.0
import Box2D 1.0

Image {
    id: screen

    property color textColor: "yellow"

    property int minutes
    property int seconds
    property string minutesString: "00"
    property string secondsString: "00"

    property variant startTime
    property variant finishTime
    property variant pauseStartTime
    property variant pauseTime: 0

    property bool dead: true
    property variant bike

    signal speedChanged(real speed)
    signal stopAudio()
    signal startAudio()
    signal splitVKB()

    property bool allowExit: false
    Component.onCompleted: {
        allowExitTimer.running = true;
    }
    
    signal purchaseCompleted(bool isActivated)
    function appPurchaseCompleted(isActivated){
        purchaseCompleted(isActivated);
    }

    function die() {
        mainTimer.stop();
        dead = true;
        stopAudio();
        screen.state = ''
        bike.freeRearWheel();
        bike.freeRearWheel();
    }

    function finish() {
        if (!dead) {
            mainTimer.stop();
            world.stop();
            stopAudio();
            finishTime = ((new Date()).getTime() - startTime - pauseTime)/1000;
            loader.source = "FinishView.qml"
            loader.item.time = finishTime;
            dead = true;
        }
    }

    function resume() {
        loader.source = "";
        screen.state = 'Game'
        mainTimer.running = true;
        pauseTime += (new Date()).getTime() - pauseStartTime;
        world.start();
        startAudio();
    }

    function newGame() {
        seconds = 0;
        minutes = 0;
        minutesString = "00"
        secondsString = "00"
        pauseTime = 0;
        bike.setAtStart();
        dead = false
        loader.source = "";
        screen.state = 'Game'
        startAudio();
        world.start();
        mainTimer.start();
        startTime = (new Date()).getTime();
    }

    function updateControls(yRot) {
        if (!dead) {
            var speed = -yRot/60*30;
            if (speed < 0) {
                speed = 0;
                bike.rearBrake();
                bike.frontBrake();
                return;
            }
            if (speed > 30)
                speed = 30;
            bike.accelerate(speed);
        }
    }

    function tiltLeft() {
        if (!dead)
            bike.leanBackward();
    }

    function tiltRight() {
        if (!dead)
            bike.leanForward();
    }

    // We want to be in landscape mode.
    width: screenSizeProvider.width > screenSizeProvider.height ?
              screenSizeProvider.width : screenSizeProvider.height;
    height: screenSizeProvider.height < screenSizeProvider.width ?
                screenSizeProvider.height : screenSizeProvider.width;

    focus: true
    source: "gfx/sky.png"
    anchors.fill: parent

    Keys.onPressed: {
        if (!dead) {
            if (event.key == Qt.Key_Up) {
                bike.accelerate(30);
            }
            if (event.key == Qt.Key_Down) {
                bike.rearBrake();
            }
            if (event.key == Qt.Key_Left) {
                bike.leanBackward();
            }
            if (event.key == Qt.Key_Right) {
                bike.leanForward();
            }
            if (event.key == Qt.Key_Space) {
                bike.frontBrake();
            }
        }
    }

    Keys.onReleased: {
        if (event.key == Qt.Key_Up || event.key == Qt.Key_Down) {
            bike.freeRearWheel();
        }
        if (event.key == Qt.Key_Space) {
            bike.freeFrontWheel();
        }
    }

    Timer {
        id: mainTimer

        repeat: true
        interval: 1000
        onTriggered: {
            if (seconds == 59) {
                seconds = 0;
                minutes++;
            }
            else
                seconds++;
            if (seconds < 10)
                secondsString = "0"+seconds
            else
                secondsString = ""+seconds
            if (minutes < 10)
                minutesString = "0"+minutes
            else
                minutesString = ""+minutes
        }
    }

    Flickable {
        anchors.fill: parent
        contentWidth: world.width
        contentHeight: world.height
        interactive: false
        contentX: bike.centerX - screen.width/3
        contentY: bike.centerY - screen.height/1.4

        // BOX2D WORLD
        World {
            id: world;
            property bool staticWorld: false

            width: 100*screen.width
            height: 2*screen.height
            gravity: Qt.point(0, -5)

            Level1 {}

            Bike {
                id: bike

                x: -100
                y: 100
            }

            // Debug
            DebugDraw {
                id: debugDraw
                z: 10
                world: world
                anchors.fill: world
                opacity: 0.75
                visible: false
            }

            //onFpsChanged: fpsText.text = fps;
        }
    }

    // Mini view
    /*Image {

        width: parent.width*0.2
        height: parent.height*0.2

        x: parent.width*0.75
        y: parent.height*0.05

        source: "sky.png"
        clip: true
        Flickable {

            contentWidth: world.width
            contentHeight: world.height
            interactive: false
            contentX: bike.centerX - screen.width/3
            contentY: bike.centerY - 1.5*screen.height
            scale: 0.1

            Image {
                id: ground2
                height: 500/900*screen.height
                anchors { left: parent.left; right: parent.right; top: parent.bottom; topMargin: -80/900*screen.height }
                fillMode: Image.Tile
                source: "grass.png"
            }
            Image {
                id: ceiling2
                height: 20
                anchors { left: parent.left; right: parent.right; bottom: parent.top }
            }
            Image {
                id: leftWall2
                width: 20
                anchors { right: parent.left; bottom: ground2.top; top: ceiling2.bottom }
            }
            Image {
                id: rightWall2
                width: 20
                anchors { left: parent.right; bottom: ground2.top; top: ceiling2.bottom }
            }

            Image {
                id: hangerSmall

                x: 4000/1500*screen.width
                y: screen.height
                width: 1000/1500*screen.width
                height: 50/900*screen.height
                source: "grass.png"
            }

            Image {
                id: jumpSmall

                x: 2*screen.width
                y: 1520/900*screen.height
                width: 350/1500*screen.width
                height: 200/900*screen.height
                source: "jump.png"
            }

            Bike {
                id: bikeSmall

                bikeBodyX: bike.bikeBodyX
                bikeBodyY: bike.bikeBodyY
                bikeRotation: bike.bikeRotation
                wheelX: bike.wheelX
                wheelY: bike.wheelY
                wheelRot: bike.wheelRot
                rearWheelX: bike.rearWheelX
                rearWheelY: bike.rearWheelY
                rearWheelRot: bike.rearWheelRot
                humanX: bike.humanX
                humanY: bike.humanY
                humanRot: bike.humanRot
                armX: bike.armX
                armY: bike.armY
                armRot: bike.armRot
                handX: bike.handX
                handY: bike.handY
                handRot: bike.handRot
                rearForkX: bike.rearForkX
                rearForkY: bike.rearForkY
                rearForkRot: bike.rearForkRot
                suspLowerX: bike.suspLowerX
                suspLowerY: bike.suspLowerY
                suspLowerRot: bike.suspLowerRot
            }
        }
    }*/

    Text {
        id: timeText
        font.pixelSize: 30
        text: minutesString + ":" + secondsString
        opacity: (loader.source == "")
        color: textColor
        anchors {
            horizontalCenter: parent.horizontalCenter
            bottom: parent.bottom
            bottomMargin: 20
        }
    }

    /*Text {
        id: fpsText
        anchors {
            left: parent.left
            leftMargin: 20
            top: parent.top
            topMargin: 20
        }
    }*/

    Rectangle {
        id: dimmedRect
        anchors.fill: parent
        color: "black"
        opacity: 0.4
        visible: true
    }


    Button {
        id: optionsButton
        name: "info"
        scale: 0.7
        onScaleChanged: {scale = 0.7}
        anchors {
            left: parent.left
            leftMargin: 1
            bottom: parent.bottom
            bottomMargin: 1
        }
        onClicked:{
            loader.source = "InfoView.qml"
            screen.state = 'InfoScreen'
        }
    }

    Button {
        id: exitButton
        name: "exit"
        scale: 0.7
        onScaleChanged: {scale = 0.7}
        anchors {
            right: parent.right
            rightMargin: 1
            bottom: parent.bottom
            bottomMargin: 1
        }
        onClicked: {
            if(screen.allowExit)
                Qt.quit();
        }
    }

    Loader {
        id: loader
        //to unify all views size that used by loader
        anchors.centerIn: parent
        width: screen.width
        height: screen.height
    }

    Menu {
        id: menu
    }

    states: [
        State {
            name: "Game"
            PropertyChanges {target: menu; opacity: 0;}
            PropertyChanges {
                target: optionsButton
                name: "options"
                onClicked: {
                    mainTimer.running = false;
                    pauseStartTime = (new Date()).getTime();
                    world.stop();
                    stopAudio();
                    screen.state = ''
                }
            }
            PropertyChanges {target: dimmedRect; visible: false}
        },
        State {
            name: "InfoScreen"
            PropertyChanges {target: menu; opacity: 0;}
            PropertyChanges {
                target: exitButton
                name: "ok"
                z:1
                onClicked: {
                    screen.state = ''
                    loader.source = ''
                }
            }
            PropertyChanges {
                target: optionsButton
                visible: false
            }
        },
        State {
            name: "BuyScreen"
            PropertyChanges {target: menu; opacity: 0;}
        }
    ]

    Timer {
        // defer application close that user cannot accidentally exit application
        // after Buy Item UX flow
        // this functionality does not affect build variant without "Buy" option
        id: allowExitTimer
        interval: 500; running: false; repeat: false
        onTriggered: {screen.allowExit = true}
    }

}
