import { Injectable } from '@angular/core';
import { MALLS } from '../mocks/malls';
import Mall, { IMall } from '../models/mall';
import { OfferService } from './offer.service';
import { OutletService } from './outlet.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { TOKEN, URL } from '../mocks/url';


@Injectable({
    providedIn: 'root'
})
export class MallService {
    malls: Array<IMall> = [];

    constructor(
        private offerService: OfferService,
        private outletService: OutletService,
        private http: HttpClient
    ) {
		this.fetchMalls();
	}

	async mallsByLocation(latitude: number, longitude: number) {
		const httpOptions = {
			headers: new HttpHeaders({
				'Access-Control-Allow-Origin': '*',
				'Content-Type': 'application/json',
				'Authorization': 'Token ' + TOKEN
			})
		};

		return await this.http.get(URL + '/api/maioraservice/mall/v1/latitude/28.6569551/longitude/77.2122032/check/', httpOptions).toPromise();
	}

    async allMalls() {
        const httpOptions = {
			headers: new HttpHeaders({
				'Access-Control-Allow-Origin': '*',
				'Content-Type': 'application/json',
				'Authorization': 'Token ' + TOKEN
			})
		};

		return await this.http.get(URL + '/api/maioraservice/mall/getallmalls/', httpOptions).toPromise();
    }

    private getDenormalizedMall = async (mall: Mall) => {
        const offers = await Promise.all(mall.offers.map(offer_id => this.offerService.getOfferByID(offer_id)));
        const outlets = await Promise.all(mall.outlets.map(outlet_id => this.outletService.getOutletByID(outlet_id)));

        return {
            ...mall,
            offers,
            outlets,
        };
    }

    public async getAllMalls() {
        return this.malls;
    }

	private async fetchMalls() {
		this.malls = await Promise.all(MALLS.map(this.getDenormalizedMall));
	}

    public async getMallByID(id: string) {
		if (this.malls.length <= 0) {
			await this.fetchMalls();
			return this.malls.find((mall) => mall.id === id);
		} else {
			return this.malls.find((mall) => mall.id === id);
		}
    }

	async updateMall(data: IMall) {
		for (let i = 0; i < this.malls.length; i += 1) {
			if (data.id === this.malls[i].id) {
				this.malls[i] = data;
			}
		}
	}
}
