package cn.reghao.devops.mgr.app.controller.page;

import cn.reghao.devops.mgr.app.db.query.AppDeployQuery;
import cn.reghao.devops.mgr.app.model.vo.AppRunningNode;
import cn.reghao.devops.mgr.app.model.vo.AppRunning;
import cn.reghao.devops.mgr.util.DefaultSetting;
import cn.reghao.devops.mgr.util.PageSort;
import cn.reghao.jutil.jdk.db.PageList;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.RequestParam;

import java.util.*;

/**
 * @author reghao
 * @date 2019-08-30 18:49:15
 */
@Slf4j
@Api(tags = "应用状态页面")
@Controller
@RequestMapping("/app/stat")
public class StatusPageController {
    private final AppDeployQuery appDeployQuery;

    public StatusPageController(AppDeployQuery appDeployQuery) {
        this.appDeployQuery = appDeployQuery;
    }

    @ApiOperation(value = "应用运行状态列表页面", notes = "N")
    @GetMapping
    public String statusPage1(@RequestParam(value = "env", required = false) String env,
                              @RequestParam(value = "type", required = false) String appType,
                              @RequestParam(value = "appName", required = false) String appName,
                              Model model) {
        if (env == null) {
            env = DefaultSetting.getDefaultEnv();
        }

        if (appType == null) {
            appType = DefaultSetting.getDefaultAppType();
        }

        if (appName != null) {
            Page<AppRunning> page = new PageImpl<>(Collections.emptyList());
            PageList<AppRunning> pageList = PageList.empty();

            model.addAttribute("env", env);
            model.addAttribute("page", page);
            model.addAttribute("list", pageList.getList());
            return "/devops/app/stat/index1";
        }

        PageRequest pageRequest = PageSort.pageRequest();
        Page<AppRunning> page = appDeployQuery.getAppRunningByPage(env, appType, pageRequest);

        model.addAttribute("env", env);
        model.addAttribute("type", appType);
        model.addAttribute("page", page);
        model.addAttribute("list", page.getContent());
        return "/devops/app/stat/index1";
    }

    @ApiOperation(value = "应用运行状态详情页面", notes = "N")
    @GetMapping(value = "/detail/{appId}")
    public String statusPage2(@PathVariable(value = "appId") String appId, Model model) {
        List<AppRunningNode> list = appDeployQuery.getAppRunning(appId);
        model.addAttribute("list", list);
        return "/devops/app/stat/index2";
    }
}
