// External Dependencies
import React, { Component } from 'react';
import jQuery from 'jquery';
import OwlCarousel from 'react-owl-carousel';
// Internal Dependencies
import './style.css';

class DPOCP_PostsCarousel extends Component {

    static slug = 'et_pb_dp_oc';

    constructor(props) {
        super(props);
        this.state = { error: null, isLoaded: false, carouselData: [] };
    }

    componentDidMount() {
        this.runAjaxQuery();
    }

    shouldComponentUpdate(nextProps, nextState) {
        if (this.state.isLoaded !== nextState.isLoaded || JSON.stringify(this.props) !== JSON.stringify(nextProps)) {
            return true;
        } else {
            return false;
        }
    }

    componentDidUpdate(prevProps) {
        const props = this.props;
        var restart_after = ['custom_query', 'number_post', 'offset_number', 'cpt_name', 'cpt_categories', 'taxonomy_tags', 'include_tags', 'exclude_tags', 'orderby', 'order', 'custom_fields', 'custom_field_names', 'custom_field_labels', 'show_post_excerpt', 'post_excerpt_length', 'remove_current_post', 'hash_thumbnail_size', 'auto_width', 'thumbnail_size', 'thumbnail_original', 'use_hash_thumbnail', 'show_post_title', 'show_author', 'show_post_category', 'show_post_date', 'show_comments', 'read_more', 'show_custom_content'];
        for (let index = 0; index < restart_after.length; index++) {
            var element = restart_after[index];
            if (props[element] !== prevProps[element]) {
                this.setState({ isLoaded: false });
                this.runAjaxQuery();
            }
        }
    }

    runAjaxQuery() {
        var component = this;
        const props = this.props;
        const url = window.et_fb_options.ajaxurl;
        const moduleClass = props.moduleInfo.type + "_" + props.moduleInfo.order;
        jQuery.ajax({
            type: 'POST',
            url: url,
            data: {
                action: 'get_carousel_html_action',
                module_props: props,
                module_class: moduleClass
            }
        }).done(function (data, textStatus, jqXHR) {
            component.setState({ isLoaded: true, carouselData: JSON.parse(data) });
        }).fail(function (jqXHR, textStatus, errorThrown) {
            component.setState({ isLoaded: true, error: errorThrown });
        });
    }

    render() {
        const props = this.props;
        const { error, isLoaded, carouselData } = this.state;
        if (error) {
            return (<div>{error}</div>);
        } else if (!isLoaded) {
            return (
                <div className="et-fb-loader-wrapper">
                    <div className="et-fb-loader"></div>
                </div>
            );
        }
        if (carouselData.error !== undefined) {
            return (
                <div className="dpocp_error">
                    <p>{carouselData.error}</p>
                </div>
            );
        } else {
            if (carouselData.no_results !== undefined) {
                return (
                    <div className="dpocp_no_results">
                        <p>{carouselData.no_results}</p>
                    </div>
                );
            } else {
                const responsive = { 0: { items: ('' === props.number_thumb_phone) ? 1 : props.number_thumb_phone }, 768: { items: ('' === props.number_thumb_tablet) ? 3 : props.number_thumb_tablet }, 981: { items: ('' === props.number_thumb) ? 5 : props.number_thumb } }; return (
                    <React.Fragment>
                        <OwlCarousel
                            center={(props.center === 'on') ? true : false}
                            rewind={(props.behavior === 'rewind') ? true : false}
                            loop={(props.behavior === 'loop') ? true : false}
                            nav={(props.show_arrow === 'on') ? true : false}
                            URLhashListener={(props.use_hash_thumbnail === 'on') ? true : false}
                            dots={(props.show_control === 'on' && props.use_hash_thumbnail !== 'on') ? true : false}
                            dotsEach={(isNaN(props.items_per_dot)) ? 3 : parseInt(props.items_per_dot)}
                            slideBy={(isNaN(props.items_per_slide)) ? 1 : parseInt(props.items_per_slide)}
                            navText={["", ""]}
                            margin={parseInt(props.item_margin)}
                            autoplay={(props.slide_auto === 'on') ? false : false}
                            autoplayTimeout={(isNaN(props.slide_speed)) ? 5000 : parseInt(props.slide_speed)}
                            autoplaySpeed={(isNaN(props.animation_speed)) ? 500 : parseInt(props.animation_speed)}
                            navSpeed={(isNaN(props.arrows_speed)) ? 500 : parseInt(props.arrows_speed)}
                            dotsSpeed={(isNaN(props.dots_speed)) ? 500 : parseInt(props.dots_speed)}
                            autoplayHoverPause={(props.slide_hover === 'on') ? true : false}
                            autoWidth={(props.auto_width === 'on') ? true : false}
                            lazyLoad={(props.lazy_load === 'on') ? true : false}
                            responsiveRefreshRate={500}
                            responsiveBaseElement={jQuery('.et-fb-mousetrap')}
                            responsive={responsive}
                        >
                            {this.renderItems()}
                        </OwlCarousel>
                        {this.renderHash()}
                    </React.Fragment>
                );
            }
        }
    }

    renderHash() {
        const moduleClass = this.props.moduleInfo.type + "_" + this.props.moduleInfo.order;
        if (this.props.use_hash_thumbnail === 'on') {
            return (
                <div className={"dp_ocp_hash_container " + this.props.hash_thumbnail_align}>
                    {
                        this.state.carouselData.hash_thumbnail_array.map((image, i) =>
                            <a href={"#" + moduleClass + "_" + i} >
                                <img className="dp_ocp_hash_image" src={image} />
                            </a>
                        )
                    }
                </div>
            );
        } else {
            return null;
        }
    }

    renderItems() {
        const Item = ({ data_hash_vb, image_vb, thumbnail, thumbnail_original, title, permalink, gallery_id, author, author_link, categories, date, comments, excerpt, post_custom_fields, custom_content }) => (
            <div className="dp_oc_item" style={{ width: image_vb + 'px' }} data-hash={data_hash_vb} >
                {this.renderThumbnail(thumbnail, thumbnail_original, permalink, title, gallery_id)}
                {this.renderTitle(title, permalink)}
                {this.renderAuthor(author, author_link)}
                {this.renderCategories(categories)}
                {this.renderDate(date)}
                {this.renderComments(comments)}
                {this.renderCustomFields(post_custom_fields)}
                {this.renderExcerpt(excerpt, permalink)}
                {this.renderCustomContent(custom_content)}
            </div>
        );
        const Items = ({ posts }) => (posts.map((post, i) => <Item key={i}{...post} />));
        return (
            <React.Fragment>
                <Items posts={this.state.carouselData.posts} />
            </React.Fragment>
        );
    }

    renderThumbnail(thumbnail, thumbnail_original, permalink, title, gallery_id) {
        if (thumbnail) {
            const lazyClass = (this.props.lazy_load === 'on') ? " owl-lazy" : "";
            const imageClassName = "dp_oc_post_thumb" + lazyClass;
            const lightboxGallery = (this.props.lightbox_gallery === 'on') ? "on" : "off";
            if (this.props.lightbox === 'on') {
                return (
                    <a href="#" data-ref={thumbnail_original} className="dp_ocp_lightbox_image" >
                        <img className={imageClassName} src={thumbnail} alt={title} data-lightbox-gallery={lightboxGallery} data-gallery-image={gallery_id} />
                    </a>
                );
            } else {
                return (
                    <a href={permalink}>
                        <img className={imageClassName} src={thumbnail} alt={title} />
                    </a>
                );
            }
        } else {
            return null;
        }
    }

    renderTitle(title, permalink) {
        if (this.props.show_post_title === 'on') {
            if (this.props.lightbox === 'on') {
                return (
                    <h2 className="dp_oc_post_title">{title}</h2>
                );
            } else {
                return (
                    <h2 className="dp_oc_post_title">
                        <a href={permalink}>{title}</a>
                    </h2>
                );
            }
        } else {
            return null;
        }
    }

    renderAuthor(author, author_link) {
        if (this.props.show_author === 'on') {
            return (
                <p className="post-meta dp_oc_post_meta dp_oc_post_author">
                    <a href={author_link}>{this.props.author_prefix_text + " " + author}</a>
                </p>
            );
        }
    }

    renderCategories(categories) {
        const Cat = ({ url, name }) => (
            <a href={url}>{name}, </a>
        );
        const Cats = ({ cats }) => (cats.map((cat, i) => <Cat key={i}{...cat} />));
        if (this.props.show_post_category === 'on' && Array.isArray(categories) && categories.length > 0) {
            return (
                <p className="post-meta dp_oc_post_meta dp_oc_post_categories">
                    <Cats cats={categories} />
                </p>
            );
        } else {
            return null;
        }
    }

    renderDate(date) {
        if (this.props.show_post_date === 'on') {
            return (
                <p className="post-meta dp_oc_post_meta dp_oc_post_date">{date}</p>
            );
        } else {
            return null;
        }
    }

    renderComments(comments) {
        if (this.props.show_comments === 'on') {
            return (
                <p className="post-meta dp_oc_post_meta dp_oc_post_commets">{comments}</p>
            );
        } else {
            return null;
        }
    }

    renderCustomFields(post_custom_fields) {
        var custom_field = [];
        for (var item in post_custom_fields) {
            if (typeof post_custom_fields[item] === 'string') {
                var cf = [];
                cf['label'] = item;
                cf['value'] = post_custom_fields[item];
                custom_field.push(cf);
            }
        }
        const CF = ({ label, value }) => (
            <p className="post-meta dp_custom_field">
                <span className="dp_custom_field_name">{label}</span>
                <span className="dp_custom_field_value">{value}</span>
            </p>
        );
        const CFs = ({ cfs }) => (cfs.map((cf, i) => <CF key={i}{...cf} />));
        if (this.props.custom_fields === 'on') {
            return (
                <React.Fragment>
                    <CFs cfs={custom_field} />
                </React.Fragment>
            );
        } else {
            return null;
        }
    }

    renderExcerpt(excerpt, permalink) {
        if (this.props.show_post_excerpt === 'on') {
            return (
                <div className="post-excerpt dp_oc_post_excerpt">
                    {excerpt}
                    {this.renderReadMore(permalink)}
                </div>
            );
        } else {
            return null;
        }
    }

    renderReadMore(permalink) {
        if (this.props.read_more === 'on') {
            return (
                <a href={permalink} className="dp_oc_read_more_link">{this.props.read_more_text}</a>
            );
        } else {
            return null;
        }
    }

    renderCustomContent(custom_content) {
        if (this.props.show_custom_content === 'on') {
            return (
                <React.Fragment>
                    {custom_content}
                </React.Fragment>
            );
        } else {
            return null;
        }
    }

    static css(props) {
        const additionalCss = [{}];
        if (props.module_bg !== undefined && props.module_bg !== '') {
            additionalCss.push([{
                selector: '%%order_class%%.et_pb_dp_oc .dp_oc_item',
                declaration: `background-color: ${props.module_bg};`
            }]);
        }
        if (props.arrow_color !== undefined && props.arrow_color !== '') {
            additionalCss.push([{
                selector: '%%order_class%%.et_pb_dp_oc .owl-carousel .owl-nav',
                declaration: `color: ${props.arrow_color};`
            }]);
        }
        if (props.control_color !== undefined && props.control_color !== '') {
            additionalCss.push([{
                selector: '%%order_class%%.et_pb_dp_oc .owl-carousel .owl-dots .owl-dot',
                declaration: `background-color: ${props.control_color};`
            }]);
        }
        if (props.control_size !== undefined && props.control_size !== '') {
            additionalCss.push([{
                selector: '%%order_class%%.et_pb_dp_oc .owl-carousel .owl-dots .owl-dot',
                declaration: `width: ${props.control_size}; height: ${props.control_size};`
            }]);
        }
        if (props.show_arrow !== undefined && props.show_arrow !== 'on') {
            additionalCss.push([{
                selector: '%%order_class%%.et_pb_dp_oc .owl-carousel .owl-nav',
                declaration: `display: none;`
            }]);
        }
        if (props.background_layout !== undefined) {
            if (props.background_layout === 'dark') {
                additionalCss.push([{
                    selector: '%%order_class%%, %%order_class%% a, %%order_class%% h2',
                    declaration: `color: #ffffff`
                }]);
                additionalCss.push([{
                    selector: '%%order_class%% .owl-dots .owl-dot',
                    declaration: `background-color: #ffffff`
                }]);
            } else {
                additionalCss.push([{
                    selector: '%%order_class%%, %%order_class%% a, %%order_class%% h2',
                    declaration: `color: #666666;`
                }]);
                additionalCss.push([{
                    selector: '%%order_class%% .owl-dots .owl-dot',
                    declaration: `background-color: #666666;`
                }]);
            }
        }
        return additionalCss;
    }
}

export default DPOCP_PostsCarousel;
