package de.avatic.lcc.controller.help;

import de.avatic.lcc.dto.help.HelpPage;
import de.avatic.lcc.service.help.MarkdownService;
import org.apache.commons.compress.utils.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/help")
public class HelpController {

    private static final Logger logger = LoggerFactory.getLogger(HelpController.class);

    private final MarkdownService markdownService;

    private final List<HelpPage> pages = List.of(
            new HelpPage("dashboard", "Dashboard"),
            new HelpPage("assistant", "Create Calculations"),
            new HelpPage("single-edit", "Single Edit"),
            new HelpPage("mass-edit-basics", "Mass Edit (Basics)"),
            new HelpPage("mass-edit-destinations", "Mass Edit (Advanced)"),
            new HelpPage("report", "Reporting"));

    @Value(value = "${lcc.help.static:}")
    private String staticStorageUrl;

    public HelpController(MarkdownService markdownService) {
        this.markdownService = markdownService;
    }

    @GetMapping({"/content", "content"})
    public List<HelpPage> listContent() {
        if(staticStorageUrl == null|| staticStorageUrl.isBlank())
            return List.of();

        return pages;
    }

    @GetMapping("/content/{resource}")
    public Map<String, String> getHelpContent(@PathVariable String resource) throws IOException {

        if (pages.stream().noneMatch(p -> p.getPage().equals(resource)))
            throw new IOException("Page not found");

        Map<String, String> map = new HashMap<>();

        var fileName = resource + ".md";
        var videoUrl = staticStorageUrl == null ? null : staticStorageUrl + "/" + resource + ".mp4";

        logger.info("Loading help content: {}", fileName);
        String html = markdownService.loadAndConvertMarkdown(fileName, resource);

        map.put("content", html);

        if (videoUrl != null)
            map.put("video", videoUrl);

        return map;

    }
}
