import { Injectable }       from '@angular/core'
import { HttpClient }             from '@angular/common/http'

import { SharedService }    from '@k-services/svc.shared'
import { HelperService }    from '@k-services/svc.helper'
import { CacheService }     from '@k-services/general/svc.cache'

import { PageType }         from '@k-types/page'

import { map } from 'rxjs/operators'
import { Observable } from 'rxjs'


@Injectable()
export class StaticBlockService {
	
	constructor(
        private http: HttpClient,
        private _shared: SharedService,
        private _helper: HelperService,
        private _cache: CacheService
    ) { }

    api: string = this._helper.server
    credentials: string = this._helper.credentials

    /**
     * Returns static block content as Object based on identifier.
     * If call has already been made the cached data is returned instead.
     * 
     * @param identifier: string
     */
    getBlockContent(identifier: string): Observable<any> {
        let result,
            cacheKey = 'static-block_' + identifier,
            cachedResult = this._cache.get(cacheKey)

        if(!!cachedResult) {
            return new Observable((observer) => {

                observer.next(cachedResult)
            })
        }
        else {
            return this.http.get(this.api + 'feed/get/static' + this.credentials + '&identifier=' + identifier)
                .pipe(
                    map((response: any) => {

                    let resp
                    let up = response.data.errorMessage

                    if(response.status.toString() === 'error')
                        throw up
                    
                    this._cache.set(cacheKey, response.data)
                    resp = response.data as PageType

                    return resp

                    })
                )
        }
    }


}
