import * as RSSFeed from 'feed'
import {appPath, Awaitable, hasOwnProperty, Maybe, Singleton} from '@extollo/lib'
import {AbstractBlog, BlogBackend, BlogPostFrontMatter, isBlogPostFrontMatter} from './AbstractBlog.service'
import {Country, isCountry} from './countries'
import * as marked from 'marked'

export type FoodBlogPostFrontMatter = BlogPostFrontMatter & {
    country: Country,
}

@Singleton()
export class FoodBlog extends AbstractBlog<FoodBlogPostFrontMatter> {
    private countryRenderCache: Partial<Record<Country, string>> = {}

    public async getCountryBlurb(country: Country): Promise<Maybe<string>> {
        if ( typeof this.countryRenderCache[country] === 'undefined' ) {
            const path = appPath('resources', 'food-blog-countries', `${country}.md`)

            let contents = ''
            if ( await path.exists() ) {
                contents = marked.marked(await path.read())
            }

            this.countryRenderCache[country] = contents
        }

        return this.countryRenderCache[country]
    }

    protected isValidFrontMatter(what: unknown): what is FoodBlogPostFrontMatter {
        return (
            isBlogPostFrontMatter(what)
            && hasOwnProperty(what, 'country')
            && isCountry(what.country)
        )
    }

    protected getBackend(): BlogBackend<FoodBlogPostFrontMatter> {
        return {
            routePrefix: '/food',
            resourcePath: ['food-blog'],
            author: {
                name: 'Garrett Mills',
                link: 'https://garrettmills.dev/#about',
                email: 'shout@garrettmills.dev',
            },
        }
    }

    protected createFeed(lastUpdated: Maybe<Date>): Awaitable<RSSFeed.Feed> {
        const feed = new RSSFeed.Feed({
            title: 'World Plate Adventures',
            description: 'World Plate Adventures is a lifetime exploration of international food.',
            id: `${this.routing.getAppUrl()}/food/about`,
            link: this.routing.getNamedPath('wpa').toRemote,
            language: 'en',
            image: this.routing.getAssetPath('favicon', 'apple-touch-icon.png').toRemote,
            favicon: this.routing.getAssetPath('favicon', 'favicon.ico').toRemote,
            copyright: `Copyright (c) ${(new Date).getFullYear()} Garrett Mills. See website for licensing details.`,
            updated: lastUpdated,
            generator: '',
            /*feedLinks: {
                json: this.routing.getNamedPath('food-blog:json').toRemote,
                atom: this.routing.getNamedPath('food-blog:atom').toRemote,
                rss: this.routing.getNamedPath('food-blog:rss').toRemote,
            },*/
            author: {
                name: 'Garrett Mills',
                email: 'shout@garrettmills.dev',
                link: 'https://garrettmills.dev/#about',
            },
        })

        feed.addCategory('Food')
        feed.addCategory('International Cuisine')

        return feed
    }
}
