package com.mzh.library.controller;

import com.mzh.library.dao.impl.JdbcSystemLogDao;
import com.mzh.library.entity.AuthenticatedUser;
import com.mzh.library.entity.SystemLogPage;
import com.mzh.library.entity.SystemLogSearchCriteria;
import com.mzh.library.service.ServiceResult;
import com.mzh.library.service.SystemLogService;
import com.mzh.library.service.impl.SystemLogServiceImpl;
import com.mzh.library.util.SessionAttributes;

import java.io.IOException;
import java.util.Collections;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SystemLogServlet extends HttpServlet {
    private static final String LOGS_JSP = "/WEB-INF/jsp/maintenance/system-logs.jsp";
    private static final String UNAUTHORIZED_JSP = "/WEB-INF/jsp/auth/unauthorized.jsp";
    private static final String DENIED_MESSAGE = "您无权查看系统日志。";

    private SystemLogService systemLogService;

    @Override
    public void init() {
        this.systemLogService = new SystemLogServiceImpl(new JdbcSystemLogDao());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SystemLogSearchCriteria criteria = new SystemLogSearchCriteria(
            request.getParameter("operationType"),
            request.getParameter("keyword"),
            request.getParameter("createdFrom"),
            request.getParameter("createdTo")
        );
        request.setAttribute("criteria", criteria);

        ServiceResult<SystemLogPage> result = systemLogService.searchLogs(currentUser(request), criteria);
        if (isPermissionDenied(result)) {
            forwardDenied(request, response, result.getMessage());
            return;
        }

        if (result.isSuccessful()) {
            request.setAttribute("logs", result.getData().getLogs());
            request.setAttribute("operationTypes", result.getData().getOperationTypes());
        } else {
            request.setAttribute("logs", Collections.emptyList());
            request.setAttribute("operationTypes", Collections.emptyList());
            request.setAttribute("errorMessage", result.getMessage());
            request.setAttribute("errors", result.getErrors());
        }

        request.getRequestDispatcher(LOGS_JSP).forward(request, response);
    }

    private boolean isPermissionDenied(ServiceResult<?> result) {
        return !result.isSuccessful() && DENIED_MESSAGE.equals(result.getMessage());
    }

    private void forwardDenied(HttpServletRequest request, HttpServletResponse response, String message)
        throws ServletException, IOException {
        response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        request.setAttribute("errorMessage", message);
        request.getRequestDispatcher(UNAUTHORIZED_JSP).forward(request, response);
    }

    private AuthenticatedUser currentUser(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        Object value = session == null ? null : session.getAttribute(SessionAttributes.AUTHENTICATED_USER);
        return value instanceof AuthenticatedUser ? (AuthenticatedUser) value : null;
    }
}
