import { NodeWrapper } from '../node_wrapper' import { Url } from '../url'

export class Frame extends NodeWrapper {

static get name(){ return 'frame' }

constructor(...args){
    super(...args)
}

get url(){
    if(this.$url === undefined){
        this.$url = Url.fromString(
            this.attributes['data-url'] || window.location,
            this.frame ? this.frame.url : window.location
        )
    }
    return this.$url
}

set url(url){
    this.$url = Url.fromString(
        url,
        this.url
    )
}

load({$method = 'GET', $url = this.url.toString(), $headers = {}, ...params }){
    if(this.request){
        this.request.abort()
    }

    $method = $method.toUpperCase();

    this.url = $url
    const isRequestBody = $method == 'POST' || $method == 'PUT' || $method == 'PATCH';
    if(!isRequestBody){
        this.url.params = {...this.url.params, ...params}
    }

    this.request = new XMLHttpRequest();

    this.request.open($method, this.url.toString(), true);

    this.request.onload = () => {
        if (this.request.status >= 200 && this.request.status < 400) {
            this.patch(this.request.response)
        }
    }

    const defaultHeaders = {};
    const document = this.document || this
    const csrfToken = document.find('meta[name="csrf-token"').map(nodeWrapper => nodeWrapper.attributes.content).pop()
    if(csrfToken){
        defaultHeaders['X-CSRF-Token'] = csrfToken
    }
    const headers = {...defaultHeaders, ...this.headers}
    Object.keys(headers).forEach((name) => this.request.setRequestHeader(name, headers[name]))

    const formData = new FormData();
    if(isRequestBody){
        Object.keys(params).forEach((name) => formData.append(name, params[name]));
    }

    this.request.send(formData)
}

}

Frame.register()