package com.lion.lionwebsite.Filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.scheduling.annotation.Scheduled;

import java.io.FileWriter;
import java.io.IOException;
import java.util.Calendar;

@WebFilter(filterName = "AdaptorFilter", urlPatterns = {"/", "/personal/"})
public class AdaptorFilter implements Filter {

    FileWriter writer;

    AdaptorFilter(){
        Calendar calendar = Calendar.getInstance();
        try {
            writer = new FileWriter(String.format("log/AccessLog_%s-%s-%s.log",
                    calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)));

        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0 0 0 * * *")
    void changeDate(){
        Calendar calendar = Calendar.getInstance();
        try {
            if(writer != null)
                writer.close();

            writer = new FileWriter(String.format("log/AccessLog_%s-%s-%s.log",
                    calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH)));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String UserAgent = request.getHeader("User-Agent");

        //屏蔽UA为null的请求
        if(UserAgent == null)
            return;

        String AuthCode = request.getParameter("AuthCode") == null ? "null" : request.getParameter("AuthCode");
        String ServletPath = request.getServletPath();
        String ip = request.getHeader("X-Forwarded-For") == null ? request.getRemoteAddr(): request.getHeader("X-Forwarded-For");
        Calendar calendar = Calendar.getInstance();
        String now = String.format("%s:%s:%s", calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));


        //日志
        System.out.printf("%s ip:%s  \tpath:%s  \tAuthCode:%s ua:%s\n", now, ip, ServletPath, AuthCode, UserAgent.length() > 61 ? UserAgent.substring(0, 60): UserAgent);
        writer.write(String.format("%s ip:%s    \tpath:%s    \tAuthCode:%s ua:%s\n", now, ip, ServletPath, AuthCode, UserAgent));
        writer.flush();

        //如果是验证，则直接跳转
        if(ServletPath.equals("/validate"))
            filterChain.doFilter(servletRequest, servletResponse);

        //如果不是，则根据UA判断是否跳转
        else if ((UserAgent.contains("Android") || UserAgent.contains("iPhone")))
            if (ServletPath.equals("/personal/") && AuthCode.equals("alone"))
                    response.sendRedirect("/mobile?AuthCode=alone");
            else
                response.sendRedirect("/mobile");
        else
            filterChain.doFilter(servletRequest, servletResponse);
    }
}
