import QtQuick 1.0
import 'database.js' as Db

MouseArea {
    id: finishView

    property variant time: 0

    property int winPlacement: getPlacement(time);
    property variant model: Db.getRankingsModel();

    function getPlacement(time) {
        if (time < model.get(0).rankTime)
            return 1;
        if (time < model.get(model.count-1).rankTime) {
            for (var i = 0; i < model.count-1; i++)
                if (time >= model.get(i).rankTime && time < model.get(i+1).rankTime)
                    return i+2;
        }
        else {
            return 0;
        }
    }
    function setRecord(placement, time, name) {
        Db.setRecord(placement, time, name);
        model.destroy();
        model = Db.getRankingsModel();
    }

    onClicked: {
        if (winPlacement)
            setRecord(winPlacement, time, nameField.name);
        //loader.source = "Menu.qml"
        screen.state = ''
    }

    Rectangle {
        anchors.fill: parent
        color: "black"
        opacity: 0.4
    }

    Text {
        id: timeText

        anchors.centerIn: parent
        font.pixelSize: 40
        color: textColor
        text: "Your time was: " + time
    }

    Rectangle {
        id: nameField

        property alias name: nameInput.text

        opacity: winPlacement
        color: "transparent"
        width: parent.width/3
        height: parent.height/8
        border {
            color: textColor
            width: 2
        }
        anchors {
            horizontalCenter: parent.horizontalCenter
            bottom: timeText.top
            bottomMargin: height
        }
        Text {
            id: hintText
            opacity: 0.6
            color: textColor
            anchors.centerIn: parent
            font.pixelSize: parent.height*0.5
            text: nameInput.text == "" ? "Enter your name" : ""
        }
        TextInput {
            id: nameInput
            font.pixelSize: hintText.font.pixelSize
            width: parent.width*0.8
            height: parent.height*0.8
            anchors.centerIn: parent
            color: textColor
            onFocusChanged: {
                if (focus)
                    splitVKB();
            }
        }
    }

    Button {
        anchors {
            top: timeText.bottom
            horizontalCenter: parent.horizontalCenter
        }
        name: "ok"
        onClicked: {
            if (winPlacement)
                setRecord(winPlacement, time, nameField.name);
            loader.source = ""
            screen.state = ''
        }
    }
}
