package com.mzh.library.controller;

import com.mzh.library.dao.impl.JdbcReportDao;
import com.mzh.library.entity.AuthenticatedUser;
import com.mzh.library.entity.ReportCenter;
import com.mzh.library.service.ReportService;
import com.mzh.library.service.ServiceResult;
import com.mzh.library.service.impl.ReportServiceImpl;
import com.mzh.library.util.SessionAttributes;

import java.io.IOException;

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 ReportServlet extends HttpServlet {
    private static final String REPORT_JSP = "/WEB-INF/jsp/reports/dashboard.jsp";
    private static final String UNAUTHORIZED_JSP = "/WEB-INF/jsp/auth/unauthorized.jsp";

    private ReportService reportService;

    @Override
    public void init() {
        this.reportService = new ReportServiceImpl(new JdbcReportDao());
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServiceResult<ReportCenter> result = reportService.loadReportCenter(currentUser(request));
        if (isPermissionDenied(result)) {
            forwardDenied(request, response, result.getMessage());
            return;
        }

        if (result.isSuccessful()) {
            request.setAttribute("reportCenter", result.getData());
        } else {
            request.setAttribute("errorMessage", result.getMessage());
        }

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

    private boolean isPermissionDenied(ServiceResult<?> result) {
        return !result.isSuccessful()
            && "您无权查看报表。".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;
    }
}
