package com.cloudhandson.ddsbackoffice.web;

import com.cloudhandson.ddsbackoffice.domain.DdsQueryResult;
import com.cloudhandson.ddsbackoffice.service.DdsQueryService;
import com.cloudhandson.vpdbackoffice.service.PermissionService;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class DdsController {

  private final DdsQueryService service;
  private final PermissionService permissionService;

  public DdsController(DdsQueryService service, PermissionService permissionService) {
    this.service = service;
    this.permissionService = permissionService;
  }

  @GetMapping("/")
  public String home(Model model) {
    try {
      model.addAttribute("roles", permissionService.findRoles());
      model.addAttribute("permissions", permissionService.findPermissionViews());
    } catch (DataAccessException exception) {
      model.addAttribute("roles", List.of());
      model.addAttribute("permissions", List.of());
      model.addAttribute("runtimeError", exception.getMessage());
    }
    model.addAttribute("vectorObject", service.vectorObject());
    model.addAttribute("configuredUserCount", service.users().stream().filter(user -> user.configured()).count());
    return "dds-home";
  }

  @GetMapping("/dds")
  public String page(Model model) {
    model.addAttribute("vectorObject", service.vectorObject());
    return "dds";
  }

  @PostMapping("/dds/query")
  public String query(
      @RequestParam String userKey,
      @RequestParam String sourceKey,
      @RequestParam(required = false) String searchText,
      @RequestParam(defaultValue = "20") int limit,
      Model model
  ) {
    DdsQueryResult result;
    try {
      result = service.query(userKey, sourceKey, searchText, limit);
    } catch (IllegalArgumentException e) {
      result = new DdsQueryResult(
          userKey, sourceKey, userKey, sourceKey, "-", false,
          "입력값을 확인하세요.", e.getMessage(), null, null, null, java.util.List.of()
      );
    }
    addOptions(model, userKey, sourceKey, result);
    return "dds";
  }

  private void addOptions(Model model, String userKey, String sourceKey, DdsQueryResult result) {
    var users = service.users();
    model.addAttribute("users", users);
    model.addAttribute("configuredUserCount", users.stream().filter(user -> user.configured()).count());
    model.addAttribute("sources", service.sources());
    model.addAttribute("selectedUser", userKey);
    model.addAttribute("selectedSource", sourceKey);
    model.addAttribute("queryResult", result);
  }
}
