import { Injectable } from '@angular/core';

type ICacheItem = {
    options: string;
    result: any;
};

@Injectable({
    providedIn: 'root',
})
export class CacheService {
    private requestsMap = new Map<string, ICacheItem>();
    private timer: number;
    private INVALID_TIMEOUT = 30 * 1000;

    set(key: string, options: string, result: any) {
        if (this.timer) {
            clearTimeout(this.timer);
        }

        this.requestsMap.set(key, { options, result });

        this.timer = setTimeout(() => {
            this.requestsMap.delete(key);
        }, this.INVALID_TIMEOUT) as any;
    }

    get(key: string, options: string) {
        const persisted = this.requestsMap.get(key);

        // if (options !== persisted?.options) {
        //     return undefined;
        // }

        return persisted?.result;
    }

    delete(key: string) {
        this.requestsMap.delete(key);
    }
}
