import WebSite from "../domain/WebSite";
import WebSiteRepository from "../domain/WebSiteRepository";

const CACHE_SIZE: number = 5;

export default class WebSiteService {

    public webSiteRepository: WebSiteRepository;
    public mountedWebSiteList: WebSite[];
    
    constructor(webSiteRepository: WebSiteRepository) {
        this.webSiteRepository = webSiteRepository;
        this.mountedWebSiteList = [];
    }

    public addWebSiteInCache(webSite: WebSite): void {
        if (this.mountedWebSiteList.length >= CACHE_SIZE) {
            this.mountedWebSiteList.shift();
        }
        this.mountedWebSiteList[this.mountedWebSiteList.length] = webSite;
    }

    public createWebSite(webSite: WebSite): Promise<string> {
        this.addWebSiteInCache(webSite);
        return this.webSiteRepository.add(webSite);
    }

    public updateWebSite(webSite: WebSite): Promise<string> {
        this.mountedWebSiteList.forEach( (mounted, index, mountedList) => {
            if (mounted.id === webSite.id) {
                mountedList[index] = webSite;
            }
        })
        return this.webSiteRepository.update(webSite);
    }

    public findWebSiteById(id: string): Promise<WebSite> {
        if (id === undefined || id === null) {
            throw new Error('Cannot find WebSite with null or undefined Id');
        } 
        
        let foundWebSite = this.mountedWebSiteList.find(webSite => webSite.id === id);
        if (foundWebSite) {
            return Promise.resolve(foundWebSite);
        } 
        return this.webSiteRepository.findWebSiteById(id)
            .then( webSite => {
                if (webSite === undefined || webSite === null) {
                    throw new Error('Cannot find WebSite, no such id');
                } else {
                    this.addWebSiteInCache(webSite);
                    return webSite;
                }
            });
    }
}
