declare var fetch;

import {Util} from '../../../util/util';

export class Node {

    data: any;
    dataRelationships = {};
    _headers = {
        'Accept': 'application/vnd.api+json',
        'Content-Type': 'application/vnd.api+json'
    };

    _nodeTemplate = {
        data: {
            type: "node--page",
            attributes: {
                "title": "new: node--page",
                // "langcode": "en",
                // "status": true,
                // "promote": false,
                // "sticky": false,
                // "default_langcode": true,
                "body": {
                    "value": "new: node--page: body",
                    // "format": "full_html",
                    // "summary": ""
                }
            }
        }
    };


    constructor() {

    }

    _createNode(nodeObject: any = this._nodeTemplate) {
        let node = Util.copy(this._nodeTemplate);
        node = Util.deepAssign(node, nodeObject);

        console.log(node);
        return node;
    }

    _json() {
        return JSON.stringify(this.data);
    }

    private async _fetchResource(url: string, params: any = undefined) {
        if (params) {
            url += '?';
            Object.keys(params).forEach(key => url += key + '=' + params[key] + '&');
        }
        let resource: any = await fetch(url, {headers: this._headers})
            .then((response) => {
                if (response.status >= 400) {
                    throw new Error('Bad response from server');
                }
                return response.json();
            })
            .then((data) => {
                return data;
            });
        return resource;
    }


}
