import {appPath, Controller, Inject, Injectable, plaintext, view} from '@extollo/lib'
import {Home} from './Home.controller'
import * as marked from 'marked'
import {MarkMarkService} from '../../services/MarkMark.service'
import {MarkMarkBlog} from '../../services/blog/MarkMarkBlog.service'

@Injectable()
export class MarkMark extends Controller {
    @Inject()
    protected readonly markmark!: MarkMarkService

    @Inject()
    protected readonly blog!: MarkMarkBlog

    public welcome() {
        const home = <Home> this.make(Home)
        return view('markmark:welcome', {
            ...home.getThemeCSS(),
            title: 'MarkMark (v1.1)',
        })
    }

    private cachedStandard?: string

    public async standard() {
        if ( !this.cachedStandard ) {
            const path = appPath('resources', 'markmark', 'standard.md')
            const content = await path.read()
            this.cachedStandard = marked.marked(content)
        }

        const home = <Home> this.make(Home)
        return view('markmark:standard', {
            ...home.getThemeCSS(),
            title: 'Spec: MarkMark (v1.1)',
            contentHtml: this.cachedStandard,
        })
    }

    public async linksHtml() {
        const home = <Home> this.make(Home)
        return view('links', {
            ...home.getThemeCSS(),
            title: 'Bookmarks',
            contentHtml: await this.markmark.getLinksHTML(),
        })
    }

    public async linksMarkMark() {
        return plaintext(await this.markmark.getLinksMM())
            .contentType('text/markdown;variant=markmark')
    }

    public async rss() {
        const feed = await this.blog.getFeed()
        return plaintext(feed.rss2()).contentType('application/rss+xml; charset=UTF-8')
    }

    public async atom() {
        const feed = await this.blog.getFeed()
        return plaintext(feed.atom1()).contentType('application/atom+xml; charset=UTF-8')
    }

    public async json() {
        const feed = await this.blog.getFeed()
        return plaintext(feed.json1()).contentType('application/feed+json; charset=UTF-8')
    }
}
