import { Host, h } from "@stencil/core";
import { fb } from '../../utils/utils';
export class BbProfile {
    constructor() {
        this.root = '/';
        this.profileHeader = 'overlay';
        this.filter = {
            collection: '',
            model: '',
            manufacturer: '',
            location: ''
        };
        this.linkClickHandler = (path) => (ev) => {
            let event = this.linkClick.emit({
                path: path
            });
            if (event.defaultPrevented) {
                ev.preventDefault();
            }
        };
        this.loadCount = 6;
        this.loadMoreRefHandler = (button) => {
            if ('IntersectionObserver' in window) {
                if (button) {
                    this.loadMoreIntersectionObserver && this.loadMoreIntersectionObserver.disconnect();
                    this.loadMoreIntersectionObserver = new IntersectionObserver(data => {
                        if (data[0].isIntersecting) {
                            this.loadCount = this.loadCount + 6;
                        }
                    });
                    this.loadMoreIntersectionObserver.observe(button);
                }
                else {
                    // ref is called with null when removed so remove the observer        
                    this.loadMoreIntersectionObserver && this.loadMoreIntersectionObserver.disconnect();
                }
            }
        };
        this.loadMoreClickHandler = () => {
            this.loadCount = this.loadCount + 6;
        };
    }
    async componentWillLoad() {
        // Handles is a list so we must do a query and grab the first item
        const profilesSnaphot = await fb.firestore().collection('profiles').where('handles', 'array-contains', this.profilePath).get();
        this.profileSnaphot = profilesSnaphot.docs && profilesSnaphot.docs[0];
        if (this.profileSnaphot) {
            // TODO - use attached collections NOT a query
            this.collectionsSnaphot = await fb.firestore().collection('collections').where('uid', '==', this.profileSnaphot.get('uid')).get();
        }
    }
    async componentWillUpdate() {
        // Handles is a list so we must do a query and grab the first item
        const profilesSnaphot = await fb.firestore().collection('profiles').where('handles', 'array-contains', this.profilePath).get();
        this.profileSnaphot = profilesSnaphot.docs && profilesSnaphot.docs[0];
        if (this.profileSnaphot) {
            // TODO - use attached collections NOT a query
            this.collectionsSnaphot = await fb.firestore().collection('collections').where('uid', '==', this.profileSnaphot.get('uid')).get();
        }
    }
    watchFilterHandler() {
        // Reset the load count
        this.loadCount = 6;
    }
    render() {
        if (!this.profileSnaphot)
            return h(Host, null, "Loading...");
        else if (!this.profileSnaphot.exists)
            return h(Host, null, "Missing!");
        else {
            const profile = this.profileSnaphot.data();
            const collections = this.collectionsSnaphot && this.collectionsSnaphot.docs.map(doc => ({
                id: doc.id,
                ref: doc.ref,
                data: doc.data()
            }));
            //const featuredCollection = collections && collections[0];
            // Combine all collections
            let allListings = collections && collections.reduce((prev, collection) => prev.concat(collection.data.listings), []);
            // Only unique
            allListings = allListings && allListings.filter((obj, index, arr) => arr.findIndex(f => (f.id === obj.id)) === index);
            const models = allListings && [...new Set(allListings.map(l => l.data.specifications.model).filter(Boolean))];
            const manufacturers = allListings && [...new Set(allListings.map(l => l.data.specifications.manufacturer).filter(Boolean))];
            const locations = allListings && [...new Set(allListings.map(l => l.data.location).filter(Boolean))];
            let filteredListings = allListings;
            if (this.filter.collection) {
                filteredListings = filteredListings && collections.filter(({ id }) => id == this.filter.collection)[0].data.listings;
            }
            if (this.filter.model) {
                filteredListings = filteredListings && filteredListings.filter(l => l.data.specifications.model == this.filter.model);
            }
            if (this.filter.manufacturer) {
                filteredListings = filteredListings && filteredListings.filter(l => l.data.specifications.manufacturer == this.filter.manufacturer);
            }
            if (this.filter.location) {
                filteredListings = filteredListings && filteredListings.filter(l => l.data.location == this.filter.location);
            }
            const filteredCount = filteredListings ? filteredListings.length : 0;
            filteredListings = filteredListings && filteredListings.slice(0, this.loadCount);
            return h(Host, null,
                this.profileHeader == 'overlay' && h("div", { class: "header", style: { backgroundImage: profile.header && profile.header.info && profile.header.info.secure_url && `url('${profile.header.info.secure_url}')` } },
                    h("svg", { viewBox: "0 0 2 1", style: { display: 'block', width: '100%' } }),
                    h("div", { class: "header-overlay" },
                        profile.avatar && profile.avatar.info && profile.avatar.info.secure_url && h("img", { src: profile.avatar.info.secure_url, class: "header-avatar" }),
                        h("h1", { style: { margin: '0.5rem 1rem' } }, profile.name),
                        h("div", { style: { display: 'none', margin: '0.5rem 1rem' } }, profile.summary))),
                collections && h("div", { style: { display: 'flex', margin: '-0.5rem 0.5rem', overflow: 'auto' } }, collections.map((collection) => (h("a", { onClick: this.linkClickHandler(`collections/${collection.id}`), href: `${this.root}collections/${collection.id}`, class: `collection-header collection-header-${collection.id}` },
                    h("svg", { viewBox: "0 0 4 1", style: { display: 'block', width: '100%' } }),
                    h("div", { style: { position: 'absolute', left: '0', width: '100%', bottom: '0', padding: '0.5rem' } }, collection.data.title))))),
                h("form", { style: { display: 'none' }, class: "search-form" },
                    h("select", { class: "search-form-select", onChange: ({ target }) => this.filter = Object.assign(Object.assign({}, this.filter), { location: target.value }) },
                        h("option", { selected: this.filter.location == '', value: "" }, "All Locations"),
                        locations && locations.map(location => h("option", { selected: this.filter.location == location, value: location }, location))),
                    h("select", { class: "search-form-select", onChange: ({ target }) => this.filter = Object.assign(Object.assign({}, this.filter), { model: target.value }) },
                        h("option", { selected: this.filter.model == '', value: "" }, "All Models"),
                        models && models.map(model => h("option", { selected: this.filter.model == model, value: model }, model))),
                    h("select", { class: "search-form-select", onChange: ({ target }) => this.filter = Object.assign(Object.assign({}, this.filter), { manufacturer: target.value }) },
                        h("option", { selected: this.filter.manufacturer == '', value: "" }, "All Manufacturers"),
                        manufacturers && manufacturers.map(manufacturer => h("option", { selected: this.filter.manufacturer == manufacturer, value: manufacturer }, manufacturer)))),
                filteredListings && h("div", { class: "card-grid" },
                    filteredListings.map(listing => h("div", { class: "card-grid-item" },
                        h("bb-listing-card", { listingId: listing.id, listingData: listing.data, root: this.root }))),
                    h("div", { class: "card-grid-item" })),
                (this.loadCount < filteredCount) && h("button", { ref: this.loadMoreRefHandler, onClick: this.loadMoreClickHandler }, "Load More"));
        }
    }
    static get is() { return "bb-profile"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() { return {
        "$": ["bb-profile.css"]
    }; }
    static get styleUrls() { return {
        "$": ["bb-profile.css"]
    }; }
    static get properties() { return {
        "profilePath": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "profile-path",
            "reflect": false
        },
        "root": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "root",
            "reflect": false,
            "defaultValue": "'/'"
        },
        "profileHeader": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "'none' | 'overlay' | 'image'",
                "resolved": "\"image\" | \"none\" | \"overlay\"",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "profile-header",
            "reflect": false,
            "defaultValue": "'overlay'"
        }
    }; }
    static get states() { return {
        "profileSnaphot": {},
        "collectionsSnaphot": {},
        "filter": {},
        "loadCount": {}
    }; }
    static get events() { return [{
            "method": "linkClick",
            "name": "linkClick",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": ""
            },
            "complexType": {
                "original": "any",
                "resolved": "any",
                "references": {}
            }
        }]; }
    static get watchers() { return [{
            "propName": "filter",
            "methodName": "watchFilterHandler"
        }]; }
}
