import QtQml
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
import QtQuick.Dialogs

import LocalDir
import LocalCommand
import RemoteCommand

Rectangle {
    id: thiz
    color: Playbook.backgroundColor
    property var output

    LocalCommand {
        id: local
        onCommandStart: function() {
            output.append("command start")
        }

        onCommandFinished:  function() {
            output.append("command finish")
        }

        onDataArrived: function(data){
            output.append(data)
        }
    }

    RemoteCommand {
        id: remote
        onSubcommandStart: function(host, command) {
            output.append(host+": command start: "+command)
        }

        onSubcommandFinished: function(host, code) {
            output.append(host+": command finish: exit code: "+code)
        }

        onDataArrived: function(host, data) {
            output.append(data)
        }
        onErrorArrived: function(error) {
            output.append(error)
        }
    }

    Timer {
        id: mytimer
        interval: 1000
        repeat: false
        running: false

        function sleep(ms) {
            return new Promise(function(resolve, reject) {
                let fnOnTriggered = function(){
                    mytimer.triggered.disconnect(fnOnTriggered)
                    Qt.callLater(resolve);
                }
                mytimer.triggered.connect(fnOnTriggered)
                mytimer.interval = ms;
                mytimer.start()
            });
        }
    }

    Button{
        anchors.centerIn: parent
        text: "Run script"
        onClicked: function() {
            let name = Playbook.hostChooser()
            if(name.length <= 0) {
                return;
            }
            remote.hosts = [name];
            asyncGenerator(function *(){
                Playbook.openTerminal();
                thiz.output = Playbook.terminal();
                for(let i = 0; i < 10; i++) {
                    //---
                    output.append("-----------local command: "+i)
                    yield localCommand(local, "ls ~").catch(function(){})
                    //---
                    output.append("-----------sleep for a second "+i)
                    yield mytimer.sleep(1000);
                    //---
                    output.append("-----------remote command:  "+i)
                    yield remoteCommand(remote, "ls ~")
                }
               // Playbook.closeTerminal();
            })();
        }
    }
}
