import { Component, h, Host, Prop, State, Watch, Event } from '@stencil/core';
import { cdnAsset, buildMetaData } from '../../utils/utils';
import { Head } from 'stencil-head';
import { orderBy } from 'natural-orderby';
import groupArray from 'group-array';
//let BB_API = 'http://localhost:5000/api'
let BB_API = 'https://api.boaterbase.com/api';
//const groupBy = function (a, k) {
//  return a.reduce((acc, item) => ((acc[item[k]] = [...(acc[item[k]] || []), item]), acc), {});
//};
export class BbCollection {
    constructor() {
        this.root = '/';
        this.collectionQuery = {};
        this.collectionHeader = 'overlay';
        this.collectionList = 'overlay';
        this.collectionFilters = 'manufacturer,model';
        this.collectionLocationFilter = 'All Locations';
        this.collectionProfileFilter = 'All Profiles';
        this.loaded = false;
        this.locationFilter = '';
        this.profileFilter = '';
        this.specsFilter = {};
        this.sortOrder = 'featured';
        this.order = 'index';
    }
    get collectionFiltersList() {
        return this.collectionFilters.split(',');
    }
    get collectionId() {
        // Allow for pretty urls where the id is at the end
        return this.collectionPath.split('-').pop();
    }
    fetchData(limit = 999) {
        return fetch(`${BB_API}/collections/${this.collectionId}?limit=${limit}`, {
            headers: {
                'Accept': 'application/json',
            },
            method: 'GET'
        }).then();
    }
    async componentWillLoad() {
        //console.log('componentWillLoad')
        this.collectionResponse = await this.fetchData(6).then(response => response.json());
        if (this.collectionQuery.location) {
            this.locationFilter = this.collectionQuery.location;
        }
        if (this.collectionQuery.profile) {
            this.profileFilter = this.collectionQuery.profile;
        }
        if (this.collectionQuery.specs) {
            try {
                this.specsFilter = JSON.parse(this.collectionQuery.specs);
            }
            catch (_a) {
                this.specsFilter = {};
            }
        }
    }
    async componentDidLoad() {
        window.scrollTo(0, 0);
        // TODO - only need this load if more to load
        this.collectionResponse = await this.fetchData(999).then(response => response.json());
        this.loaded = true;
    }
    async watchPath() {
        //console.log('Path Changed', newValue, oldValue)
        this.collectionResponse = await this.fetchData().then(response => response.json());
    }
    updateRouteFilter() {
        this.linkClick.emit({
            path: `?location=${this.locationFilter}&profile=${this.profileFilter}&specs=${JSON.stringify(this.specsFilter)}`
        });
    }
    render() {
        var _a, _b, _c, _d, _e;
        if (!this.collectionResponse)
            return h(Host, null, "Loading...");
        if (!this.collectionResponse)
            return h(Host, null, "Missing");
        let collection = this.collectionResponse;
        let allListings = collection.listings || [];
        const specFilters = this.collectionFiltersList.map((key) => {
            return {
                key,
                title: 'All ' + key.charAt(0).toUpperCase() + key.slice(1) + 's',
                items: orderBy([...new Set(allListings.map(l => l.data.specifications[key]).filter(Boolean))])
            };
        });
        let allLocations = [...new Set(allListings.map(l => l.data.location && l.data.location.trim()).filter(Boolean))];
        allLocations = orderBy(allLocations);
        let splitLocations = allLocations.map((l) => {
            let ls = l.split(',').filter(Boolean).map(i => i.trim());
            return {
                country: ls.pop(),
                region: ls.pop()
            };
        });
        let groupedLocations = groupArray(splitLocations, 'country', 'region');
        //console.log(splitLocations, groupedLocations);
        let allProfiles = allListings.map(l => { var _a, _b, _c, _d, _e, _f, _g, _h; return (((_b = (_a = l.data.profile) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.handle) && { handle: (_d = (_c = l.data.profile) === null || _c === void 0 ? void 0 : _c.data) === null || _d === void 0 ? void 0 : _d.handle, name: ((_f = (_e = l.data.profile) === null || _e === void 0 ? void 0 : _e.data) === null || _f === void 0 ? void 0 : _f.name) || ((_h = (_g = l.data.profile) === null || _g === void 0 ? void 0 : _g.data) === null || _h === void 0 ? void 0 : _h.handle) }); }).filter(Boolean).filter((obj, pos, arr) => {
            return arr.map(mapObj => mapObj.handle).indexOf(obj.handle) === pos;
        });
        allProfiles = orderBy(allProfiles, [(l) => l.name]);
        // Filters
        let filteredListings = collection.listings;
        for (let specKey in this.specsFilter) {
            if (this.specsFilter[specKey]) {
                filteredListings = filteredListings.filter(l => l.data.specifications[specKey] == this.specsFilter[specKey]);
            }
        }
        if (this.locationFilter) {
            filteredListings = filteredListings.filter(l => l.data.location && l.data.location.includes(this.locationFilter));
        }
        if (this.profileFilter) {
            filteredListings = filteredListings.filter(l => { var _a, _b; return ((_b = (_a = l.data.profile) === null || _a === void 0 ? void 0 : _a.data) === null || _b === void 0 ? void 0 : _b.handle) == this.profileFilter; });
        }
        if (this.sortOrder == 'price_asc') {
            filteredListings = filteredListings.sort((a, b) => ((a.data.price || Number.MAX_VALUE) - (b.data.price || Number.MAX_VALUE)));
        }
        switch (this.sortOrder) {
            case 'price_desc':
                filteredListings = filteredListings.sort((a, b) => ((b.data.price || 0) - (a.data.price || 0)));
                break;
            case 'length_asc':
                filteredListings = filteredListings.sort((a, b) => { var _a, _b; return ((((_a = a.data.specifications) === null || _a === void 0 ? void 0 : _a.loa) || Number.MAX_VALUE) - (((_b = b.data.specifications) === null || _b === void 0 ? void 0 : _b.loa) || Number.MAX_VALUE)); });
                break;
            case 'length_desc':
                filteredListings = filteredListings.sort((a, b) => { var _a, _b; return ((((_a = b.data.specifications) === null || _a === void 0 ? void 0 : _a.loa) || 0) - (((_b = a.data.specifications) === null || _b === void 0 ? void 0 : _b.loa) || 0)); });
                break;
            case 'year_asc':
                filteredListings = filteredListings.sort((a, b) => { var _a, _b; return ((((_a = a.data.specifications) === null || _a === void 0 ? void 0 : _a.year) || Number.MAX_VALUE) - (((_b = b.data.specifications) === null || _b === void 0 ? void 0 : _b.year) || Number.MAX_VALUE)); });
                break;
            case 'year_desc':
                filteredListings = filteredListings.sort((a, b) => { var _a, _b; return ((((_a = b.data.specifications) === null || _a === void 0 ? void 0 : _a.year) || 0) - (((_b = a.data.specifications) === null || _b === void 0 ? void 0 : _b.year) || 0)); });
                break;
            case 'updated_asc':
                filteredListings = filteredListings.sort((a, b) => {
                    if (a.data.updated > b.data.updated) {
                        return 1;
                    }
                    if (a.data.updated < b.data.updated) {
                        return -1;
                    }
                    return 0;
                });
                break;
            case 'updated_desc':
                filteredListings = filteredListings.sort((a, b) => {
                    if (a.data.updated < b.data.updated) {
                        return 1;
                    }
                    if (a.data.updated > b.data.updated) {
                        return -1;
                    }
                    return 0;
                });
                break;
            case 'random':
                // Randomish by id % current day
                filteredListings = filteredListings.sort((a, b) => {
                    const rnd = (new Date()).getHours();
                    const ai = rnd % a.id.length;
                    const bi = rnd % b.id.length;
                    return a.id.charCodeAt(ai) - b.id.charCodeAt(bi);
                });
            default:
            //TODO - check for default sort option only do random if not default
        }
        const meta = buildMetaData(collection.title, collection.summary, 'website', ((_b = (_a = collection === null || collection === void 0 ? void 0 : collection.header) === null || _a === void 0 ? void 0 : _a.info) === null || _b === void 0 ? void 0 : _b.secure_url) && cdnAsset(collection.header.info, 'jpg', 't_large_image'));
        return (h(Host, null,
            h("div", { style: { display: 'none' } },
                h(Head, { data: meta })),
            this.collectionHeader == 'overlay' && h("div", { class: "header", style: { backgroundColor: (_e = (_d = (_c = collection === null || collection === void 0 ? void 0 : collection.header) === null || _c === void 0 ? void 0 : _c.info) === null || _d === void 0 ? void 0 : _d.colors[0]) === null || _e === void 0 ? void 0 : _e.color, backgroundImage: collection.header && collection.header.info && collection.header.info.secure_url && `url('${cdnAsset(collection.header.info, 'jpg', 't_large_image')}')` } },
                h("svg", { viewBox: "0 0 2 1", style: { display: 'block', width: '100%', minHeight: '300px' } }),
                h("div", { class: "header-overlay" },
                    h("div", { class: "header-text" },
                        h("h1", null, collection.title),
                        h("p", null, collection.summary)),
                    h("form", { class: "search-form" },
                        specFilters.map((f) => (h("select", { class: "search-form-select", onChange: ({ target }) => { this.specsFilter = Object.assign(Object.assign({}, this.specsFilter), { [f.key]: target.value }); this.updateRouteFilter(); } },
                            h("option", { selected: this.specsFilter[f.key] == '', value: "" }, f.title),
                            f.items.map((item) => h("option", { selected: this.specsFilter[f.key] == item, value: item }, item))))),
                        h("select", { class: "search-form-select", onChange: ({ target }) => { this.locationFilter = target.value; this.updateRouteFilter(); } },
                            h("option", { selected: this.locationFilter == '', value: '' }, this.collectionLocationFilter),
                            h("hr", null),
                            Object.keys(groupedLocations).map(c => ([h("option", { selected: this.locationFilter == c, value: c }, c), orderBy(Object.keys(groupedLocations[c])).map(r => ([h("option", { selected: this.locationFilter == `${r}, ${c}`, value: `${r}, ${c}` },
                                        "\u2014 ",
                                        r)])), h("hr", null)]))),
                        h("select", { class: "search-form-select", onChange: ({ target }) => { this.profileFilter = target.value; this.updateRouteFilter(); } },
                            h("option", { selected: this.profileFilter == '', value: "" }, this.collectionProfileFilter),
                            allProfiles.map((item) => h("option", { selected: this.profileFilter == item.handle, value: item.handle }, item.name)))))),
            filteredListings && h("form", { class: "sort-form" },
                h("h2", { class: "sort-title" },
                    this.loaded ? filteredListings.length : 'Loading',
                    " Listings"),
                h("div", { class: "sort-layout" },
                    h("button", null,
                        "Card ",
                        h("svg", { width: "21", height: "21", viewBox: "0 0 21 21", fill: "none", xmlns: "http://www.w3.org/2000/svg" },
                            h("circle", { cx: "10.5", cy: "10.5", r: "9.5", fill: "#FFB056", stroke: "#F2994A", "stroke-width": "2" }))),
                    h("button", null,
                        h("iconify-icon", { class: "iconify", "data-icon": "mdi-home" }),
                        " List"),
                    h("button", null,
                        h("i", { style: { display: 'inline-block', width: '1rem', height: '1rem', background: `url('https://api.iconify.design/ion:grid.svg')` } }),
                        h("span", null, "Gallery"))),
                h("select", { class: "sort-order", onChange: ({ target }) => { this.sortOrder = target.value; } },
                    h("option", { value: "random" }, "Sort"),
                    h("hr", null),
                    h("option", { value: "price_asc" }, "Price \u2191"),
                    h("option", { value: "price_desc" }, "Price \u2193"),
                    h("hr", null),
                    h("option", { value: "length_asc" }, "Length \u2191"),
                    h("option", { value: "length_desc" }, "Length \u2193"),
                    h("hr", null),
                    h("option", { value: "year_asc" }, "Year \u2191"),
                    h("option", { value: "year_desc" }, "Year \u2193"),
                    h("hr", null),
                    h("option", { value: "updated_asc" }, "Updated \u2191"),
                    h("option", { value: "updated_desc" }, "Updated \u2193"))),
            filteredListings && h("div", { class: "card-grid" },
                filteredListings.map(listing => {
                    let mergedListing = Object.assign(Object.assign({}, listing.data), { title: listing.title || listing.data.title, message: listing.message || listing.data.message, messageDisplay: listing.messageDisplay });
                    return h("div", { key: listing.id, class: "card-grid-item" },
                        h("bb-listing-card", { listingId: listing.id, listingData: mergedListing, root: this.root, display: this.collectionList }));
                }),
                h("div", { class: "card-grid-item" }))));
    }
    static get is() { return "bb-collection"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() { return {
        "$": ["bb-collection.css"]
    }; }
    static get styleUrls() { return {
        "$": ["bb-collection.css"]
    }; }
    static get properties() { return {
        "root": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "root",
            "reflect": false,
            "defaultValue": "'/'"
        },
        "collectionPath": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "collection-path",
            "reflect": false
        },
        "collectionQuery": {
            "type": "unknown",
            "mutable": false,
            "complexType": {
                "original": "{\n    location?: '',\n    profile?: '',\n    specs?: ''\n  }",
                "resolved": "{ location?: \"\"; profile?: \"\"; specs?: \"\"; }",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "defaultValue": "{}"
        },
        "collectionHeader": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "'none' | 'overlay' | 'image'",
                "resolved": "\"image\" | \"none\" | \"overlay\"",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "collection-header",
            "reflect": false,
            "defaultValue": "'overlay'"
        },
        "collectionList": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "'card' | 'overlay'",
                "resolved": "\"card\" | \"overlay\"",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "collection-list",
            "reflect": false,
            "defaultValue": "'overlay'"
        },
        "collectionFilters": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "collection-filters",
            "reflect": false,
            "defaultValue": "'manufacturer,model'"
        },
        "collectionLocationFilter": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "collection-location-filter",
            "reflect": false,
            "defaultValue": "'All Locations'"
        },
        "collectionProfileFilter": {
            "type": "string",
            "mutable": false,
            "complexType": {
                "original": "string",
                "resolved": "string",
                "references": {}
            },
            "required": false,
            "optional": false,
            "docs": {
                "tags": [],
                "text": ""
            },
            "attribute": "collection-profile-filter",
            "reflect": false,
            "defaultValue": "'All Profiles'"
        }
    }; }
    static get states() { return {
        "loaded": {},
        "collectionResponse": {},
        "locationFilter": {},
        "profileFilter": {},
        "specsFilter": {},
        "sortOrder": {},
        "order": {}
    }; }
    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": "collectionPath",
            "methodName": "watchPath"
        }]; }
}
