package de.nbscloud.webcontainer.controller;

import de.nbscloud.webcontainer.registry.App;
import de.nbscloud.webcontainer.registry.AppRegistry;
import de.nbscloud.webcontainer.shared.config.WebContainerSharedConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.http.HttpServletRequest;
import java.net.MalformedURLException;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.stream.Collectors;

@Controller
public class WebContainerController {

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

    @Autowired
    private WebContainerSharedConfig webContainerSharedConfig;

    @Autowired
    private AppRegistry appRegistry;

    @GetMapping("/")
    public String landing(Model model) {
        logger.info("NBSCloud started - apps available: {}", this.appRegistry.getAll().stream().map(App::getId)
                                                                             .collect(Collectors.joining(", ")));

        return "redirect:dashboard";
    }

    @GetMapping("/toggleDarkMode")
    public String toggleDarkMode(Model model, HttpServletRequest httpServletRequest) {
        String navigateTo = "/";

        try {
            final String fullPath = new URL(httpServletRequest.getHeader("referer")).toURI().getPath();
            // FIXME - will break if the app is deployed on http://host/a/b/financer instead of http://host/financer
            final String tmpPath = StringUtils.removeStart(fullPath, "/");
            navigateTo = tmpPath.substring(tmpPath.indexOf("/"));
        } catch (MalformedURLException | URISyntaxException | StringIndexOutOfBoundsException e) {
            // TODO
            e.printStackTrace();
        }

        this.webContainerSharedConfig.setDarkMode(!this.webContainerSharedConfig.isDarkMode());

        return "redirect:" + navigateTo;
    }

}
