const { ServerSideRender, PanelBody, SelectControl, Toolbar } = wp.components;
const { __ } = wp.i18n;
const { Fragment, Component } = wp.element;
const { InspectorControls, BlockControls } = wp.blockEditor;

export default class Edit extends Component {
    constructor(  { attributes, setAttributes }  ) {
        super();
        this.state = {
            giveaways: []
        }
        this.props = { attributes, setAttributes };
        this.get_giveaways = this.get_giveaways.bind(this);
        this.startLibraries = this.startLibraries.bind(this);
    }

    componentDidMount() {
        this.get_giveaways();
    }

    get_giveaways() {
        var self = this;
        fetch( window.ajaxurl, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
            },
            body: 'action=sg_get_available_giveaways',
            credentials: 'same-origin'
        }).then(function (res) {
            return res.json();
        }).then(function (res) {
            if ( res.success ) {
                self.setState({ giveaways: res.data })
            }
        });
    }

    startLibraries( timeout = 1000 ) {
        const self = this;
        setTimeout( function() {
            self.maybeStartCountdown();
        }, timeout );
    }

    /**
     * Maybe Start Countdown
     */
    maybeStartCountdown() {
        var $           = jQuery,
            $countdowns = $(".giveasap_countdown:not(.countdown-started)");

        if( $countdowns.length ) {
            $countdowns.each(function(){
                var $timestamp = $(this).attr("data-end");
                $(this).countdown({
                    until: new Date($timestamp * 1000), format: 'dHMS'});
            }).addClass('countdown-started');
        }
    }

    render() {
        let giveaways = [{ label: __( 'Select a Giveaway' ), value: 0 }]
        const { attributes, setAttributes, isSelected } = this.props;
        let message = '';
        let blockContent = <p>{ __( 'Please, select a giveaway to show' ) }</p>;
        const selectedID = parseInt( attributes.id );

        if ( this.state.giveaways.length ) {
            giveaways = giveaways.concat(this.state.giveaways.map(( post ) => {
                return { label: post.post_title, value: post.ID }
            }));
        } else {
            giveaways = [];
        }

        if ( 0 === giveaways.length ) {
            message = <p>{ __( 'No Giveaways found.' )}</p>;
        }

        if ( parseInt( attributes.id ) > 0 ) {
            if ( typeof ServerSideRender !== 'undefined' ) {
                blockContent = <ServerSideRender
                    block="simple-giveaways/countdown"
                    attributes={attributes}
                />;
            } else {

                blockContent = <wp.serverSideRender
                    block="simple-giveaways/countdown"
                    attributes={attributes}
                />;
            }
            this.startLibraries();
        }

        return (
            <Fragment>
                <InspectorControls>
                    <PanelBody
                        title={ __( 'Display Options' ) }
                        initialOpen={ true } >
                        { giveaways.length > 1 && [
                            <SelectControl
                                label={ __( 'Giveaway' ) }
                                value={ selectedID }
                                options={ giveaways }
                                onChange={ ( id ) => {
                                    setAttributes( { id: id } );
                                    this.startLibraries();
                                }
                                }
                            />,
                        ]}
                        { message }
                    </PanelBody>
                </InspectorControls>
                <BlockControls>
                    <Toolbar controls={ [ {
                        icon: `image-rotate`,
                        title: `Reload countdown/slider if not started`,
                        isActive: false,
                        onClick: () => {
                            this.startLibraries(100);
                        },
                    }] } />
                </BlockControls>
                { blockContent }

            </Fragment>);
    }
}