package com.mzh.library.controller;

import com.mzh.library.dao.impl.JdbcBorrowRecordDao;
import com.mzh.library.entity.AuthenticatedUser;
import com.mzh.library.entity.BorrowRecord;
import com.mzh.library.service.ServiceResult;
import com.mzh.library.service.impl.BorrowingServiceImpl;
import com.mzh.library.util.SessionAttributes;

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

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 ReaderLoanHistoryServlet extends HttpServlet {
    private static final String HISTORY_JSP = "/WEB-INF/jsp/reader/loans.jsp";
    private static final String UNAUTHORIZED_JSP = "/WEB-INF/jsp/auth/unauthorized.jsp";
    private static final String HISTORY_DENIED_MESSAGE = "您无权查看借阅历史。";

    private BorrowingServiceImpl borrowingService;

    @Override
    public void init() {
        this.borrowingService = new BorrowingServiceImpl(new JdbcBorrowRecordDao());
    }

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

        request.setAttribute("borrowRecords", result.isSuccessful() ? result.getData() : Collections.emptyList());
        if (result.isSuccessful() && result.getMessage() != null && !result.getMessage().isEmpty()) {
            request.setAttribute("successMessage", result.getMessage());
        }
        if (!result.isSuccessful()) {
            request.setAttribute("errorMessage", result.getMessage());
        }

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

    private boolean isPermissionDenied(ServiceResult<?> result) {
        return !result.isSuccessful() && HISTORY_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;
    }
}
