var Observable = require("data/observable").Observable;
var taskList = require('../../shared/view-models/task-list-view-model');
const frameModule = require("ui/frame");

var pageData = new Observable({
    taskList: taskList.tasks
});

function pageLoaded(args) {
    var page = args.object;
    page.bindingContext = pageData;
    if (taskList.tasks.length === 0)  {
        // lokale dummy daten
        taskList.load();

        // daten per http vom server holen
        // server wird per node.js im verzeichnis server über die index.js-Datei gestartet
        // taskList.fetchList();
    }

    writeFile();

}

function writeFile() {
    const fs = require('file-system');
    var documents = fs.knownFolders.documents();
    var path = fs.path.join(documents.path, "myfile.txt");
    var file = fs.File.fromPath(path);
    file.writeText("Something").then(() => {
        file.readText()
            .then(function (content) {
                console.log('file content: ', content);
            });
    })
}

/*
function fetchList() {
    fetch('http://myServer.com/tasks')
        .then(response => response.json())
        .then(response => taskList.load(response));
}
*/

function toggleState(event) {
    taskList.toggleState(event.object.id);  
}

function create() {
    const topmost = frameModule.topmost();
    topmost.navigate("views/form/form");
}

module.exports = {
    pageLoaded,
    toggleState,
    create
}
