package cn.reghao.bnt.web.admin.service;

import cn.reghao.bnt.web.admin.db.repository.AccessLogRepository;
import cn.reghao.bnt.web.admin.db.repository.RuntimeLogRepository;
import cn.reghao.bnt.web.admin.model.po.AccessLog;
import cn.reghao.bnt.web.admin.model.po.RuntimeLog;
import cn.reghao.bnt.web.admin.model.vo.AccessLogInfo;
import cn.reghao.bnt.web.admin.model.vo.RuntimeLogInfo;
import cn.reghao.bnt.web.ws.handler.LogHandler;
import cn.reghao.jutil.jdk.web.log.AppLog;
import cn.reghao.jutil.web.ServletUtil;
import cn.reghao.jutil.jdk.web.log.GatewayLog;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

/**
 * @author reghao
 * @date 2024-02-05 17:13:57
 */
@Service
public class LogService {
    private final int pageSize = 100;
    private final AccessLogRepository accessLogRepository;
    private final RuntimeLogRepository runtimeLogRepository;
    private final LogHandler logHandler;

    public LogService(AccessLogRepository accessLogRepository, RuntimeLogRepository runtimeLogRepository,
                      LogHandler logHandler) {
        this.accessLogRepository = accessLogRepository;
        this.runtimeLogRepository = runtimeLogRepository;
        this.logHandler = logHandler;
    }

    public AccessLog getAccessLog() {
        GatewayLog gatewayLog = ServletUtil.getGatewayLog();
        return new AccessLog(gatewayLog);
    }

    public void saveAccessLog() {
        AccessLog accessLog = getAccessLog();
        accessLogRepository.save(accessLog);
        logHandler.sendAccessLog(new AccessLogInfo(accessLog));
    }

    public Page<AccessLogInfo> getAccessLogs(int pageNumber) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = PageRequest.of(pageNumber-1, pageSize, sort);
        Page<AccessLogInfo> page = accessLogRepository.findAll(pageRequest).map(AccessLogInfo::new);
        return page;
    }

    public void eraseAccessLog() {
        accessLogRepository.deleteAll();
    }

    public void consumeAppLog(AppLog appLog) {
        RuntimeLog runtimeLog = new RuntimeLog(appLog);
        runtimeLogRepository.save(runtimeLog);
    }

    public Page<RuntimeLogInfo> getRuntimeLogs(int pageNumber) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        PageRequest pageRequest = PageRequest.of(pageNumber-1, pageSize, sort);
        Page<RuntimeLogInfo> page = runtimeLogRepository.findAll(pageRequest).map(RuntimeLogInfo::new);
        return page;
    }

    public void eraseRuntimeLog() {
        runtimeLogRepository.deleteAll();
    }
}
