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

export class Form extends NodeWrapper {

static get name(){ return 'form' }

static get selector(){ return 'form, .form' }

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

    this.on('submit', (event) => {
        console.log('Form submit', event)
        event.preventDefault();
        this.frame.load({$method: this.method, $url: this.url, ...this.params })
    })
}

get method(){
    return this.attributes['method'] || this.attributes['data-method'] || 'POST'
}

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

get inputs(){
    return this.descendants.filter((descendant) => descendant.isInput)
}

get params(){
    const out = {}
    this.inputs.forEach(input => {
        const value = input.value
        if(value !== undefined){
            out[input.name] = value
        }
    })
    return out
}

}

Form.register()