import { Injectable } from '@angular/core';
import Outlet, { IOutlet } from '../models/outlet';
import { OUTLETS } from '../mocks/outlets';
import { OfferService } from './offer.service';
import { MenuItemService } from './menu-item.service';

@Injectable({
    providedIn: 'root'
})
export class OutletService {
    outlets: Array<IOutlet>

    constructor(
        private offerService: OfferService,
        private menuItemService: MenuItemService
    ) {
        this.fetchOutlets();
    }

    private getDenormalizedOutlet = async (outlet: Outlet) => {
        const offers = await Promise.all(outlet.offers.map(offer_id => {
            return this.offerService.getOfferByID(offer_id);
        }));
        const menu_items = await Promise.all(outlet.menu_items.map(menu_item_id => this.menuItemService.getMenuItemByID(menu_item_id)));

        return {
            ...outlet,
            offers,
            menu_items,
        };
    }

    public async fetchOutlets() {
        this.outlets = await Promise.all(OUTLETS.map(this.getDenormalizedOutlet));
    }

	async getAllOutlets() {
		this.outlets = await Promise.all(OUTLETS.map(this.getDenormalizedOutlet));
		return this.outlets;
	}

    public async getOutletByID(id: string) {
        await this.fetchOutlets();
        return this.outlets.find((outlet) => outlet.id === id);
    }
}
