import { Component } from "/kirui/core/component";
import { registry } from "/kirui/core/registry";
import {createRef, h, render,hydrate} from 'preact';
import $ from "jquery";


class KrAjaxPanel extends Component {
    constructor(props) {
        super(props);
        props.ref = createRef();
        this.handleStateChange = this.handleStateChange.bind(this);
        document.addEventListener('state-change', this.handleStateChange);
    }

    refreshContent() {
        let e = new CustomEvent('AjaxLoading', {'bubbles': true, 'detail': {'loading': true}});
        this.base.dispatchEvent(e);

        $.post({
            url: this.props.contentUrl || window.location.href,
            data: $.param(this.state, true),
            statusCode: {
                340: function (resp) {
                    window.location.replace(resp.getResponseHeader('location'));
                    console.log(resp.getResponseHeader('location'));
                }
            }
        }).done((resp) => {
            let dom = resp;
            this.dataToCreateElement([dom]);
            this.props.children = dom[2];
            this.forceUpdate();
            let e = new CustomEvent('AjaxLoading', {'bubbles': true, 'detail': {'loading': false}});
            this.base.dispatchEvent(e);
        }).fail((resp) => {
            if (resp.status === 403) {
                let dom = resp.responseJSON;
                this.dataToCreateElement([dom]);
                this.props.children = dom[2];
                this.forceUpdate();
                let e = new CustomEvent('AjaxLoading', {'bubbles': true, 'detail': {'loading': false}});
                this.base.dispatchEvent(e);
            }
        });
    }

    doRender() {
        return <kr-ajax-panel {...this.props} onStateChange={this.handleStateChange} onReloadContent={this.handleStateChange}>{this.props.children}</kr-ajax-panel>;
    }

    handleStateChange(ev) {
        let data = this.state;
        $.extend(data, ev.detail.data);
        this.setState(data);
        if (ev.detail.forceUpdate === true) {
            this.refreshContent();
        }
    }

    componentDidMount() {
        /* this.base. */
        // window.addEventListener('state-change', this.handleStateChange);
    }
}

registry.register('kr-ajax-panel', KrAjaxPanel);

export { KrAjaxPanel }
