package com.alterdekim.hearthhack.controller;

import com.alterdekim.hearthhack.config.ObjectConfig;
import com.alterdekim.hearthhack.config.ServerConfig;
import com.alterdekim.hearthhack.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;

@Slf4j
@Controller
public class StaticController {

    private final String base_title = " | Hearthhack";

    @Autowired
    private ObjectConfig dbfConfig;

    @Autowired
    private UserService userService;

    @Autowired
    private ServerConfig serverConfig;

    @GetMapping("/rules")
    public String rulesPage(Model model) {
        model.addAttribute("title", "Rules" + base_title);
        return "rules";
    }

    @GetMapping("/")
    public String homePage(Model model) {
        model.addAttribute("title", "Home" + base_title);
        return "index";
    }

    @GetMapping("/access-denied")
    public String accessDenied(Model model) {
        model.addAttribute("title", "Access denied");
        return "403";
    }

    @GetMapping("/config")
    public ResponseEntity<String> getConfig(Model model) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if( !authentication.isAuthenticated() ) return ResponseEntity.badRequest().build();
        Long uid = 0L;
        try {
            uid = userService.findByUsername(
                    ((org.springframework.security.core.userdetails.User) authentication.getPrincipal()).getUsername()
            ).getId();
            String c = dbfConfig.getClientConfig()
                    .replace("${token}", userService.genHash(uid))
                    .replace("${port}", serverConfig.getBnetPort()+"")
                    .replace("${host}", serverConfig.getHost());
            return ResponseEntity.ok(c);
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return ResponseEntity.noContent().build();
    }
}
