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

export class Anchor extends NodeWrapper {

static get name(){ return 'anchor' }

static get selector(){ return 'a, .anchor' }

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

    this.on('click', (event) => {
        if(this.url.host == this.frame.url.host && this.url.port == this.frame.url.port){
            event.preventDefault()

            const confirm = this.attributes['data-confirm']
            const method = this.attributes['data-method'] || 'GET'
            const target = this.attributes['target'] || this.attributes['data-target'] || '_top'

            if(!confirm || window.confirm(confirm)){
                if(target == '_modal'){
                    this.document.find('html').pop().addClass('is-clipped')
                    this.document.find('body').pop().append(`<div class="modal is-active" data-url="${this.url}"></div>`).forEach((modal) => {
                        modal.$parent = this
                        modal.load({})
                    })
                } else {
                    this.frame.load({ $method: method, $url: this.url })
                }
            }
        }
    })
}

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

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

}

Anchor.register()