import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import QtQuick.Dialogs
import "../js/qmldict.js" as JsLib

ColumnLayout
{
    property var new_business: null
    Layout.fillWidth: true
    Layout.fillHeight: true
    spacing: 15
    Label
    {
        text: qsTr("Kunden anlegen")
        horizontalAlignment: Text.AlignHCenter
        Layout.fillWidth: true
        font.pixelSize: 35
    }
    CheckBox
    {
        id: checkAddContact
        text: qsTr("Ansprechpartner hinzufügen")
        Layout.alignment: Qt.AlignRight
        checked: false
        onCheckStateChanged:
        {
            checkFields()
        }
    }

    RowLayout
    {
        id: addCustomer
        Layout.fillWidth: true
        Layout.fillHeight: true
        spacing: 45
        Frame
        {
            Layout.alignment: Qt.AlignTop
            Layout.fillWidth: true
            CustomerView
            {
                id: customerView
                width: parent.width
            }
        }

        AddContact
        {
                id: addContactFrame
                visible: checkAddContact.checked
        }
    }
    RowLayout
    {
        Layout.fillHeight: true
        Layout.alignment: Qt.AlignRight
        Button
        {
            text: qsTr("Abbrechen")
            onClicked: contentStack.pop()
        }
        Button
        {
            id: saveBtn
            text: qsTr("Speichern")
            enabled: false
            onClicked:
            {
                if (!checkAddContact.checked)
                {
                    new_business = JsLib.parseForm(customerView)
                    business_model.addBusiness(new_business, 0)
                    contentStack.pop()
                }
                else
                {
                    new_business = JsLib.parseForm(customerView)
                    var new_contact = JsLib.parseForm(addContactFrame.contactGrid)
                    contact_model.addContact(new_contact)
                }
            }
        }
    }
    Item
    {
        id: spacer3
        Layout.fillHeight: true
    }

    //Component.onCompleted: contact_model.contactIdReady.connect(onContactId)

    Connections
    {
        target: contact_model

        function onContactIdReady()
        {
            var con_id = arguments[0]
            business_model.addBusiness(new_business, con_id)
            contentStack.pop()
        }
    }

    function checkFields()
    {
        if(checkAddContact.checked)
        {
            if(!customerView.checkBusinessField() || !addContactFrame.checkContactField())
                saveBtn.enabled = false
            else
                saveBtn.enabled = true
        }
        else if (!customerView.checkBusinessField())
            saveBtn.enabled = false
        else
            saveBtn.enabled = true
    }
}
