import { h } from "@stencil/core";
import firebase from 'firebase/app';
import { initializeFirebaseApp } from '../../firebase';
var CustomerDataState;
(function (CustomerDataState) {
    CustomerDataState[CustomerDataState["LOADED"] = 0] = "LOADED";
    CustomerDataState[CustomerDataState["LOADING"] = 1] = "LOADING";
    CustomerDataState[CustomerDataState["FAILED"] = 2] = "FAILED";
    CustomerDataState[CustomerDataState["UNAUTHORIZED"] = 3] = "UNAUTHORIZED";
})(CustomerDataState || (CustomerDataState = {}));
export class Customers {
    constructor() {
        this.viewCustomers = [];
        this.customerDataState = CustomerDataState.LOADING;
        initializeFirebaseApp();
    }
    async componentWillLoad() {
        try {
            const customersSnapshot = await firebase.firestore().collection('customer').get();
            const customerDocuments = customersSnapshot.docs;
            const viewCustomers = [];
            for (const customerDocument of customerDocuments) {
                try {
                    const customerData = customerDocument.data();
                    // We don't want the generic customer in the selection UI
                    //
                    if (customerData.name !== 'generic') {
                        const logoPath = await firebase.storage().ref(customerData.logoPath).getDownloadURL();
                        const viewCustomer = {
                            name: customerData.name,
                            logoPath,
                            baseEnvironments: customerData.baseEnvironments
                        };
                        viewCustomers.push(viewCustomer);
                    }
                    this.customerDataState = CustomerDataState.LOADED;
                }
                catch (error) {
                    console.error('[eva-config-picker-customer] error getting customer data for', customerDocument);
                }
            }
            this.viewCustomers = viewCustomers;
        }
        catch (error) {
            if (error.code === 'permission-denied') {
                this.customerDataState = CustomerDataState.UNAUTHORIZED;
                console.error('[eva-config-picker-customer] error loading customer info, this user is not authorized', error);
            }
            else {
                this.customerDataState = CustomerDataState.FAILED;
                console.error('[eva-config-picker-customer] error loading customer info', error);
            }
        }
    }
    async selectCustomer(customer) {
        const baseEnvironments = [];
        for (const baseEnvironment of customer.baseEnvironments) {
            const baseEnvironmentDocumentData = await baseEnvironment.get();
            const baseEnvironmentData = baseEnvironmentDocumentData.data();
            baseEnvironments.push(baseEnvironmentData);
        }
        this.selectedCustomer = Object.assign(Object.assign({}, customer), { baseEnvironments });
    }
    render() {
        if (this.customerDataState === CustomerDataState.LOADING) {
            return this.renderLoading();
        }
        else if (this.customerDataState === CustomerDataState.LOADED) {
            return (h("div", null, this.selectedCustomer ?
                // If we currently have base environments, we will render those
                //
                this.renderBaseEnvironments() :
                // Otherwise we will render the customers
                //
                this.renderCustomers()));
        }
        else if (this.customerDataState === CustomerDataState.FAILED) {
            return h("div", { class: "error-feedback" }, "Error loading.");
        }
        else if (this.customerDataState === CustomerDataState.UNAUTHORIZED) {
            return this.renderShowUnauthorizedError();
        }
    }
    renderLoading() {
        return (h("div", { class: "loading-container" },
            h("eva-config-picker-spinner", null),
            h("span", null, "Loading customers...")));
    }
    renderShowUnauthorizedError() {
        return (h("div", null,
            h("span", { class: "error-feedback" }, "You are not allowed to view this data.  "),
            h("button", { class: "md", onClick: () => this.logout() }, "LOGOUT")));
    }
    renderCustomers() {
        return (h("div", { class: "grid-container" }, this.viewCustomers.map(customer => this.renderCustomerCard(customer))));
    }
    renderCustomerCard(customer) {
        return (h("div", { class: "card", onClick: () => this.selectCustomer(customer) },
            h("img", { src: customer.logoPath, alt: `${customer.name} logo` }),
            h("h3", null, customer.name)));
    }
    renderBaseEnvironments() {
        return (h("div", { class: "base-environments-list" },
            h("button", { class: "md back-button", onClick: () => this.selectedCustomer = null },
                h("div", { class: "back-icon" }, "\u2794")),
            h("div", { class: "card" },
                h("img", { src: this.selectedCustomer.logoPath, alt: `${this.selectedCustomer.name} logo` }),
                h("h3", null, this.selectedCustomer.name)),
            this.selectedCustomer.baseEnvironments.map(baseEnvironment => h("div", { class: "base-environments-list-item" },
                h("h4", null, baseEnvironment.type),
                h("p", null,
                    baseEnvironment.endpoint,
                    h("eva-config-picker-endpoint-status", { endpoint: baseEnvironment.endpoint }),
                    h("button", { class: "md", onClick: () => this.selectEndpoint(baseEnvironment) }, "SELECT"))))));
    }
    async logout() {
        try {
            await firebase.auth().signOut();
        }
        catch (error) {
            console.error('[eva-config-picker-customer] error logging out', error);
        }
    }
    selectEndpoint(baseEnvironment) {
        this.endPointSelect.emit(baseEnvironment);
    }
    static get is() { return "eva-config-picker-customer"; }
    static get encapsulation() { return "shadow"; }
    static get originalStyleUrls() { return {
        "$": ["picker-customers.scss"]
    }; }
    static get styleUrls() { return {
        "$": ["picker-customers.css"]
    }; }
    static get states() { return {
        "viewCustomers": {},
        "selectedCustomer": {},
        "customerDataState": {}
    }; }
    static get events() { return [{
            "method": "endPointSelect",
            "name": "endPointSelect",
            "bubbles": true,
            "cancelable": true,
            "composed": true,
            "docs": {
                "tags": [],
                "text": "This will emit whenever an endpoint is selected"
            },
            "complexType": {
                "original": "BaseEnvironment",
                "resolved": "BaseEnvironment",
                "references": {
                    "BaseEnvironment": {
                        "location": "local"
                    }
                }
            }
        }]; }
}
