/*
 * Block libraries
 */
const {__} = wp.i18n;
// Get registerBlockType and Editable from wp.blocks
const {registerBlockType} = wp.blocks;
const {PanelBody, ToggleControl} = wp.components;
const {Component, createElement, Fragment} = wp.element;
const {InspectorControls} = wp.editor;
const hasMultipleLocations = yoastSeoLocal.hasMultipleLocations;

import Select from 'react-select';

class yoastSeoLocalAddress extends Component {
    static getInitialState(selectedLocation) {
        return {
            locations: [],
            selectedLocation: selectedLocation,
            options: [],
        }
    }

    constructor() {
        // Get all arguments from parent class.
        super(...arguments);

        // Maybe we have a previously selected post. Try to load it.
        this.state = this.constructor.getInitialState(this.props.attributes.selectedLocation);

        // Bind so we can use 'this' inside the method.
        this.getOptions = this.getOptions.bind(this);
        this.updateLocation = this.updateLocation.bind(this);
    }

    componentDidMount() {
        const {attributes} = this.props;

        this.getOptions();
        if (!hasMultipleLocations) {
            this.updateLocation();
        }

        if (attributes.selectedLocation) {
            this.updateLocation(attributes.selectedLocation);
            this.setState({output: __('Loading...')});
        } else {
            if (hasMultipleLocations) {
                this.setState({output: __('Please select a location.')});
            }
        }
    }

    /**
     * Loading Locations.
     */
    getOptions() {
        wpseoApi.get("wpseo_locations", (locations) => {
            let options = {};
            locations.forEach((location) => {
                options[location.ID] = {value: location.ID, label: location.label};
            });
            this.setState({options});
        });
    }

    updateLocation() {
        const {
            attributes: {
                hideName,
                hideCompanyAddress,
                showOnOneLine,
                showState,
                showCountry,
                showPhone,
                showPhone2nd,
                showFax,
                showEmail,
                showURL,
                showLogo,
                showVatId,
                showTaxId,
                showCocId,
                showPriceRange,
                showOpeningHours,
                hideClosedDays
            },
            attributes,
            setAttributes
        } = this.props;

        const {selectedLocation} = (hasMultipleLocations ? this.state : '');

        if (hasMultipleLocations && selectedLocation !== attributes.selectedLocation) {
            setAttributes({selectedLocation});
            this.setState({selectedLocation});
        }

        setAttributes({hideName});
        setAttributes({hideCompanyAddress});
        setAttributes({showOnOneLine});
        setAttributes({showState});
        setAttributes({showCountry});
        setAttributes({showPhone});
        setAttributes({showPhone2nd});
        setAttributes({showFax});
        setAttributes({showEmail});
        setAttributes({showURL});
        setAttributes({showLogo});
        setAttributes({showVatId});
        setAttributes({showTaxId});
        setAttributes({showCocId});
        setAttributes({showPriceRange});
        setAttributes({showOpeningHours});
        setAttributes({hideClosedDays});

        jQuery.ajax({
            type: 'post',
            dataType: 'json',
            url: yoastSeoLocal.ajax_url,
            data: {
                action: 'wpseo_local_show_address_ajax_cb',
                id: selectedLocation,
                hideName: hideName,
                hideCompanyAddress: hideCompanyAddress,
                showOnOneLine: showOnOneLine,
                showState: showState,
                showCountry: showCountry,
                showPhone: showPhone,
                showPhone2nd: showPhone2nd,
                showFax: showFax,
                showEmail: showEmail,
                showURL: showURL,
                showLogo: showLogo,
                showVatId: showVatId,
                showTaxId: showTaxId,
                showCocId: showCocId,
                showPriceRange: showPriceRange,
                showOpeningHours: showOpeningHours,
                hideClosedDays: hideClosedDays
            },
            success: (function (response) {
                this.setState({output: response});
            }).bind(this),
            error: function (error) {
                console.log(error)
            }
        });
    }

    /**
     * Render output to screen.
     */
    render() {
        const {
            attributes: {
                hideName,
                hideCompanyAddress,
                showOnOneLine,
                showState,
                showCountry,
                showPhone,
                showPhone2nd,
                showFax,
                showEmail,
                showURL,
                showLogo,
                showVatId,
                showTaxId,
                showCocId,
                showPriceRange,
                showOpeningHours,
                hideClosedDays
            },
            setAttributes,
        } = this.props;

        const {selectedLocation} = this.state;

        return [
            // If we are focused on this block, create the inspector controls.
            <Fragment key='fragment'>
                <InspectorControls key='inspector'>
                    <PanelBody title={__('Yoast Local SEO Address Settings')}>
                        {this.state.options && hasMultipleLocations
                            ? <Select
                                // Selected value.
                                value={this.state.options[selectedLocation]}
                                options={Object.values(this.state.options)}
                                placeholder={__('Please select a location')}
                                onChange={({value}) =>
                                    this.setState({selectedLocation: value}, this.updateLocation)
                                }/>
                            : <span>{__('Loading locations')}</span>
                        }
                        <ToggleControl
                            label={__('Hide company name')}
                            checked={hideName}
                            onChange={() => {
                                setAttributes({hideName: !hideName});
                                this.setState({hideName: hideName}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Hide company address')}
                            checked={hideCompanyAddress}
                            onChange={() => {
                                setAttributes({hideCompanyAddress: !hideCompanyAddress});
                                this.setState({hideCompanyAddress: !hideCompanyAddress}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show address on one line')}
                            checked={showOnOneLine}
                            onChange={() => {
                                setAttributes({showOnOneLine: !showOnOneLine});
                                this.setState({showOnOneLine: !showOnOneLine}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show state')}
                            checked={showState}
                            onChange={() => {
                                setAttributes({showState: !showState});
                                this.setState({showState: !showState}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show country')}
                            checked={showCountry}
                            onChange={() => {
                                setAttributes({showCountry: !showCountry});
                                this.setState({showCountry: !showCountry}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show phone number')}
                            checked={showPhone}
                            onChange={() => {
                                setAttributes({showPhone: !showPhone});
                                this.setState({showPhone: !showPhone}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show second phone number')}
                            checked={showPhone2nd}
                            onChange={() => {
                                setAttributes({showPhone2nd: !showPhone2nd});
                                this.setState({showPhone2nd: !showPhone2nd}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show fax number')}
                            checked={showFax}
                            onChange={() => {
                                setAttributes({showFax: !showFax});
                                this.setState({showFax: !showFax}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show e-mail address')}
                            checked={showEmail}
                            onChange={() => {
                                setAttributes({showEmail: !showEmail});
                                this.setState({showEmail: !showEmail}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show URL')}
                            checked={showURL}
                            onChange={() => {
                                setAttributes({showURL: !showURL});
                                this.setState({showURL: !showURL}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show logo')}
                            checked={showLogo}
                            onChange={() => {
                                setAttributes({showLogo: !showLogo});
                                this.setState({showLogo: !showLogo}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show VAT number')}
                            checked={showVatId}
                            onChange={() => {
                                setAttributes({showVatId: !showVatId});
                                this.setState({showVatId: !showVatId}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show tax ID')}
                            checked={showTaxId}
                            onChange={() => {
                                setAttributes({showTaxId: !showTaxId});
                                this.setState({showTaxId: !showTaxId}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show CoC number')}
                            checked={showCocId}
                            onChange={() => {
                                setAttributes({showCocId: !showCocId});
                                this.setState({showCocId: !showCocId}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show price range')}
                            checked={showPriceRange}
                            onChange={() => {
                                setAttributes({showPriceRange: !showPriceRange});
                                this.setState({showPriceRange: !showPriceRange}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Show opening hours')}
                            checked={showOpeningHours}
                            onChange={() => {
                                setAttributes({showOpeningHours: !showOpeningHours});
                                this.setState({showOpeningHours: !showOpeningHours}, this.updateLocation);
                            }}
                        />
                        <ToggleControl
                            label={__('Hide closed days')}
                            checked={hideClosedDays}
                            onChange={() => {
                                setAttributes({hideClosedDays: !hideClosedDays});
                                this.setState({hideClosedDays: !hideClosedDays}, this.updateLocation);
                            }}
                        />
                    </PanelBody>
                </InspectorControls>
                <div dangerouslySetInnerHTML={{__html: this.state.output}}/>
            </Fragment>
        ]
    }
}

/**
 * Register example block
 */
registerBlockType(
    'yoast-seo-local/address',
    {
        title: 'Yoast SEO: Local - ' + __('Address'),
        category: 'common',
        icon: 'admin-home',
        keywords: [
            __('Address'),
            __('Yoast'),
            __('Local'),
        ],
        attributes: {
            selectedLocation: {
                type: 'number',
                default: 0,
            },
            hideName: {
                type: 'boolean',
                default: false
            },
            hideCompanyAddress: {
                type: 'boolean',
                default: false
            },
            showOnOneLine: {
                type: 'boolean',
                default: false
            },
            showState: {
                type: 'boolean',
                default: true
            },
            showCountry: {
                type: 'boolean',
                default: false
            },
            showPhone: {
                type: 'boolean',
                default: true
            },
            showPhone2nd: {
                type: 'boolean',
                default: true
            },
            showFax: {
                type: 'boolean',
                default: true
            },
            showEmail: {
                type: 'boolean',
                default: true
            },
            showURL: {
                type: 'boolean',
                default: false
            },
            showLogo: {
                type: 'boolean',
                default: false
            },
            showVatId: {
                type: 'boolean',
                default: false
            },
            showTaxId: {
                type: 'boolean',
                default: false
            },
            showCocId: {
                type: 'boolean',
                default: false
            },
            showPriceRange: {
                type: 'boolean',
                default: false
            },
            showOpeningHours: {
                type: 'boolean',
                default: false
            },
            hideClosedDays: {
                type: 'boolean',
                default: false,
            },
        },
        edit: (yoastSeoLocalAddress),
        save(props) {
            const {attributes} = props;
            let shortcode = [];

            shortcode.push('id="' + attributes.selectedLocation + '"');
            shortcode.push('hide_name="' + attributes.hideName + '"');
            shortcode.push('hide_address="' + attributes.hideCompanyAddress + '"');
            shortcode.push('oneline="' + attributes.showOnOneLine + '"');
            shortcode.push('show_state="' + attributes.showState + '"');
            shortcode.push('show_country="' + attributes.showCountry + '"');
            shortcode.push('show_phone="' + attributes.showPhone + '"');
            shortcode.push('show_phone_2="' + attributes.showPhone2nd + '"');
            shortcode.push('show_fax="' + attributes.showFax + '"');
            shortcode.push('show_email="' + attributes.showEmail + '"');
            shortcode.push('show_url="' + attributes.showURL + '"');
            shortcode.push('show_vat="' + attributes.showVatId + '"');
            shortcode.push('show_tax="' + attributes.showTaxId + '"');
            shortcode.push('show_coc="' + attributes.showCocId + '"');
            shortcode.push('show_price_range="' + attributes.showPriceRange + '"');
            shortcode.push('show_logo="' + attributes.showLogo + '"');
            shortcode.push('show_opening_hours="' + attributes.showOpeningHours + '"');
            shortcode.push('hide_closed="' + attributes.hideClosedDays + '"');

            return (
                <div className={props.className}>
                    [wpseo_address { shortcode.join(' ') } ]
                </div>
            )
        }
    },
);
