import Foundation

final class FeedPageGenerator {

    let results: PageGenerationResults

    let content: Content

    init(content: Content, results: PageGenerationResults) {
        self.content = content
        self.results = results
    }

    private func includeSwiper(in headers: inout Set<HeaderElement>) {
        if let swiperCss = content.settings.posts.swiperCssFile {
            headers.insert(.css(file: swiperCss, order: HeaderElement.swiperCssFileOrder))
            results.require(file: swiperCss)
        }
        if let swiperJs = content.settings.posts.swiperJsFile {
            headers.insert(.js(file: swiperJs, defer: true))
            results.require(file: swiperJs)
        }
    }

    func generatePage(language: ContentLanguage,
                      posts: [FeedEntryData],
                      title: String?,
                      description: String?,
                      image: FileResource?,
                      pageUrl: String,
                      pageTitle: String?,
                      pageNumber: Int,
                      totalPages: Int,
                      languageButtonUrl: String,
                      linkPrefix: String) -> String {
        var headers = content.postPageHeaders
        var footer = ""
        if posts.contains(where: { $0.requiresSwiper }) {
            // Sort swiper style sheet before default style sheet
            includeSwiper(in: &headers)
            footer = swiperInitScript(posts: posts)
        }

        let iconUrl = content.settings.navigation.localized(in: language).rootUrl
        let languageButton = NavigationBar.Link(
            text: language.next.rawValue,
            url: languageButtonUrl)

        let imageUrl = image?.linkPreviewImage(results: results)

        let requiredIcons: Set<PageIcon> = posts.reduce(into: []) { icons, post in
            icons.formUnion(post.labels.map { $0.icon })
        }

        let pageHeader = PageHeader(
            language: language,
            title: title ?? pageTitle,
            description: description,
            image: imageUrl,
            pageUrl: pageUrl,
            iconUrl: iconUrl,
            languageButton: languageButton,
            links: content.navigationBar(in: language),
            headers: headers,
            icons: requiredIcons)

        let page = GenericPage(
            header: pageHeader,
            additionalFooter: footer) { content in
                if let pageTitle {
                    content += "<h1 class='separated-headline'>\(pageTitle)</h1>"
                }
                for post in posts {
                    content += FeedEntry(data: post).content
                }
                if totalPages > 1 {
                    content += PostFeedPageNavigation(
                        linkPrefix: linkPrefix,
                        currentPage: pageNumber,
                        numberOfPages: totalPages).content
                }
            }
        return page.content
    }

    func swiperInitScript(posts: [FeedEntryData]) -> String {
        var result = "<script> window.onload = () => { "
        for post in posts {
            guard post.requiresSwiper else {
                continue
            }
            result += ImageGallery.swiperInit(id: post.entryId)
        }
        result += "}; </script>"
        return result
    }
}
