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


function get_current_content_id() {
    // Remove ? and then construct an array of objects.
    const params = window.location.search.replace('?', '').split('&').map( (param) => {
            const args = param.split('=');
    return { tag: args[0], value: args[1]};
});

    let id = 'current';
    if ( params.length ) {
        for( var querystring in params ) {
            const object = params[ querystring ];
            if ( 'post' === object['tag'] ) {
                id = object['value'];
            }
        }
    }

    return id;
}

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.maybeStartSlider = this.maybeStartSlider.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.maybeStartSlider();
            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');
        }
    }
    
    /**
     * Maybe Start the Slider
     */
    maybeStartSlider() {
        if ( jQuery('.sg-giveaway-prizes-slider:not(.slick-started)').length ) {
            jQuery(".sg-giveaway-prizes-slider:not(.slick-started)").slick({
                // normal options...
                infinite: true,
                slidesToShow: 1,
                slidesToScroll: 1,
                arrows: false,
                dots: true
            }).addClass('slick-started');
        }
    }

    render() {
        let giveaways = [{ label: __( 'Select a Giveaway' ), value: 0 }]
        const { attributes, setAttributes } = 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/giveaway"
                    attributes={attributes}
                />;
            } else {

                blockContent = <wp.serverSideRender
                    block="simple-giveaways/giveaway"
                    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 ) => {
                                this.startLibraries();
                                return setAttributes( { id: id } );
                                } 
                            }
                            />,
                            <RadioControl 
                                label={ __( 'Show Giveaway Title' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.title }
                                onChange={ (title) => {
                                    setAttributes( { title: title } );
                                    this.startLibraries( 2000 );
                                }}
                            />,
                            <RadioControl 
                                label={ __( 'Show Giveaway Content' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.content }
                                onChange={ (value) => {
                                    setAttributes( { content: value } );
                                    this.startLibraries(2000);
                                }}
                            />,
                            <RadioControl
                                label={ __( 'Show Rules' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.rules }
                                onChange={ (value) => {
                                    setAttributes( { rules: value } );
                                    this.startLibraries(2000);
                                }}
                            />,
                            <RadioControl 
                                label={ __( 'Show Prizes' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.prizes }
                                onChange={ (value) => {
                                    setAttributes( { prizes: value } );
                                    this.startLibraries(2000);
                                }}
                            />,
                            <RadioControl 
                                label={ __( 'Show Total Entries' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.show_total_entries }
                                onChange={ (value) => {
                                    setAttributes( { show_total_entries: value } );
                                    this.startLibraries(2000);
                                }}
                            />,
                            <RadioControl 
                                label={ __( 'Show Your Entries' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.show_entries }
                                onChange={ (value) => {
                                    setAttributes( { show_entries: value } );
                                    this.startLibraries(2000);
                                }}
                            />,
                            <RadioControl 
                                label={ __( 'Countdown in Header' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.countdown_in_header }
                                onChange={ (value) => {
                                    setAttributes( { countdown_in_header: value } );
                                    this.startLibraries(2000);
                                }}
                            />,
                            <RadioControl 
                                label={ __( 'Hide Winners Number' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.hide_winners_number }
                                onChange={ (value) => {
                                    setAttributes( { hide_winners_number: value } );
                                    this.startLibraries(2000);
                                }}
                            />,
                            <RadioControl 
                                label={ __( 'Hide Prize Value' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.hide_prize_value }
                                onChange={ (value) => {
                                    setAttributes( { hide_prize_value: value } );
                                    this.startLibraries(2000);
                                }}
                            />,
                            <RadioControl 
                                label={ __( 'Hide Prize Title' ) }
                                options={[
                                    { value: '0', label: __( 'No' ) },
                                    { value: '1', label: __( 'Yes' ) }
                                ]}
                                selected={ attributes.hide_prize_title }
                                onChange={ (value) => {
                                    setAttributes( { hide_prize_title: value } );
                                    this.startLibraries(2000);
                                }}
                            />
                        ]}
                        { 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>);
    }
}