package web.ParkingRecordRelated;

import pojo.ParkingRecord;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

@WebServlet("/main/sort_record")

public class sort_record extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        /*<option value="st">开始时间</option>
        <option value="et">结束时间</option>
        <option value="fee">停车费用</option>
        <option value="license">车牌号</option>*/
        Comparator<ParkingRecord> byStartTime = new Comparator<ParkingRecord>() {
            @Override
            public int compare(ParkingRecord r1, ParkingRecord r2) {
                if((r1.getStart_time()).before(r2.getStart_time()))
                    return 1;
                else return -1;}
        };
        Comparator<ParkingRecord> byEndTime = new Comparator<ParkingRecord>() {
            @Override
            public int compare(ParkingRecord r1, ParkingRecord r2) {
                if((r1.getEnd_time()).before(r2.getEnd_time()))
                    return 1;
                else return -1;// 假设 getStartTime 返回的是 Comparable 类型
            }
        };
        Comparator<ParkingRecord> byParkingFee = new Comparator<ParkingRecord>() {
            @Override
            public int compare(ParkingRecord r1, ParkingRecord r2) {
                if(r1.getParking_fee()>(r2.getParking_fee()))
                    return 1;
                else return -1;// 假设 getStartTime 返回的是 Comparable 类型
            }
        };
        String type=request.getParameter("type");
        String way=request.getParameter("order");
        HttpSession session=request.getSession();
        List<ParkingRecord> list=(List<ParkingRecord>) session.getAttribute("spot_record");
        if(type.equals("st"))
        {
            Collections.sort(list, byStartTime);
            if(way.equals("asc"))
                Collections.reverse(list);
        }
        else if(type.equals("et"))
        {
            Collections.sort(list, byEndTime);
            if(way.equals("asc"))
                Collections.reverse(list);
        }else if(type.equals("fee"))
        {
            Collections.sort(list, byParkingFee);
            if(way.equals("desc"))
            {
                Collections.reverse(list);
            }
        }
        session.setAttribute("spot_record",list);
        request.getRequestDispatcher(request.getParameter("path")).forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }
}


