package com.apobates.forum.thrones.admin.controller;

import com.apobates.forum.member.service.MemberActiveRecordsService;
import com.apobates.forum.thrones.admin.controller.helper.AdminUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
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 org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.apobates.forum.utils.lang.CommonBean;
import com.apobates.forum.utils.DateTimeUtils;
import com.google.gson.Gson;
import java.util.stream.Collectors;

/**
 * 仪表盘(Dashboard)控制器
 *
 * @author xiaofanku@live.cn
 * @since 20190321
 */
@Controller
@RequestMapping(value = "/recent")
public class AdminHomeRecentController {
    @Autowired
    private MemberActiveRecordsService memberActiveRecordsService;
    private final static Logger logger = LoggerFactory.getLogger(AdminHomeRecentController.class);
    
    @GetMapping(path = "/home")
    public String home(HttpServletRequest request, Model model) {
        // java Env
        Map<String, String> javaEnv = Map.ofEntries(
            Map.entry("vm", System.getProperty("java.vm.name")),
            Map.entry("vm.vendor", System.getProperty("java.vm.vendor")),
            Map.entry("vm.mode", System.getProperty("java.vm.info")),
            Map.entry("version", System.getProperty("java.version")),
            Map.entry("specification", System.getProperty("java.specification.version")));
        model.addAttribute("javaEnv", javaEnv);
        // os Env
        Map<String, String> osEnv = Map.ofEntries(
            Map.entry("name", System.getProperty("os.name")),
            Map.entry("version", System.getProperty("os.version")),
            Map.entry("arch", System.getProperty("os.arch")),
            Map.entry("cpu.endian", System.getProperty("sun.cpu.endian")),
            Map.entry("cpu.processor", Runtime.getRuntime().availableProcessors() + ""));
        model.addAttribute("osEnv", osEnv);
        model.addAttribute("hmp", calcRuntimeMemoryPercent());
        //近七天会员的活跃情况
        LocalDateTime finish = LocalDateTime.now();
        LocalDateTime start = DateTimeUtils.beforeDayForDate(finish, 7);
        //没有数据填上0
        TreeMap<String, Long> data = memberActiveRecordsService.groupMemberForActivity(start, finish);
        if (null == data || data.size() < 7) {
            data = AdminUtils.fillEmptyResult(start, finish, data);
        }
        List<CommonBean> rs = data.entrySet().stream().map(entry->new CommonBean(entry.getValue(), entry.getKey())).collect(Collectors.toList());
        model.addAttribute("rs", new Gson().toJson(rs));
        return "admin/index";
    }
    
    @GetMapping(path = "/stats/device/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Float> groupMemberDeviceForGroup(HttpServletRequest request, Model model) {
        Map<String, Long> data = memberActiveRecordsService.statsDevice();
        if (!data.isEmpty()) {
            final long total = data.values().stream().reduce(0L, (x, y) -> x + y);
            return data.entrySet().stream().collect(Collectors.toMap(entry->entry.getKey(), entry->entry.getValue() / Float.valueOf(total * 1.00f) * 100));
        }
        return Collections.emptyMap();
    }
    
    @GetMapping(path = "/stats/isp/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Long> groupMemberISPForGroup(HttpServletRequest request, Model model) {
        return memberActiveRecordsService.statsIsp();
    }
    
    @GetMapping(path = "/stats/province/json", produces = "application/json;charset=UTF-8")
    @ResponseBody
    public Map<String, Long> groupMemberProvinceForGroup(HttpServletRequest request, Model model) {
        return memberActiveRecordsService.statsProvince();
    }
    
    private int calcRuntimeMemoryPercent() {
        double tm = Runtime.getRuntime().totalMemory() / (1024 * 1024);
        double fm = Runtime.getRuntime().freeMemory() / (1024 * 1024);
        double pm = (tm - fm) / tm * 100;
        BigDecimal bg = new BigDecimal(pm).setScale(2, RoundingMode.UP);
        return bg.intValue();
    }
}