var ObservableArray = require("data/observable-array").ObservableArray;

const taskListViewModel = {
    
    tasks: new ObservableArray([]),

    load(tasks = []) {
        while(this.tasks.length > 0) {
            this.tasks.pop();
        }

        if (tasks.length === 0) {
            tasks = [
                {id: 1, title: 'taskA', state: 'open'},
                {id: 2, title: 'taskB', state: 'done'},
                {id: 3, title: 'taskC', state: 'open'}
            ];
        }
        this.tasks.push(tasks);
    },

    fetchList() {
        // damit unter iOS die Serverkommunikation funktioniert, muss in der Datei
        // App_Resources/iOS/Info.plist folgender Eintrag hinzugefügt werden:
        // <key>NSAppTransportSecurity</key>
        // <dict>
        //     <key>NSAllowsArbitraryLoads</key>
        //     <true/>
        // </dict>

        fetch('http://localhost:8080/tasks')
            .then(response => {
                const data = response.json(); 
                return data;
            })
            .then(response => this.load(response))
            .catch((e) => {
                console.log(e);
            });
    },

    add(task) {
        this.tasks.push({
            id: this.nextId(),
            title: task,
            state: 'open'
        });
    },

    nextId() {
        return this.tasks.reduce(
            (prev, curr) => prev > curr.id ? prev : curr.id, 0
        ) + 1;
    },

    toggleState(id) { 
        this.tasks.forEach((task, index) => {
            if (task.id == id) {
                task.state = task.state === 'open' ? 'done' : 'open';
                this.tasks.setItem(index, task);
            }
        });
    }
}

module.exports = taskListViewModel;