package web.ParkingRecordRelated;

import pojo.ParkingRecord;
import service.ParkingRecordService;
import service.ParkingSpotService;

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 java.io.IOException;
import java.sql.Timestamp;

@WebServlet(urlPatterns = "/main/admin/adminUpdateRecord")
public class UpdateRecordServlet extends HttpServlet {
    ParkingRecordService service = new ParkingRecordService();
    ParkingSpotService service1 = new ParkingSpotService();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String car_license = req.getParameter("plate");
        // 查找时间最近的car_license的记录
        try {
            ParkingRecord latestParkingRecord = service.getLatestRecord(car_license);
            if(latestParkingRecord != null && latestParkingRecord.getEnd_time() == null) {
                // 如果end_time == null, 更新该记录的end_time, 扣费
                int spot_id = latestParkingRecord.getSpot_id();
                service.updateEndTime(latestParkingRecord.getRecord_id(), new Timestamp(System.currentTimeMillis()));
                // 扣费
                service1.releaseSpot(spot_id);
            }
            else {
                // 如果end_time != null, 插入一条新的记录
                ParkingRecord newRecord = new ParkingRecord(
                        new Timestamp(System.currentTimeMillis()),
                        car_license
                );
                service.addNewRecord(newRecord);
                latestParkingRecord = service.getLatestRecord(car_license);
                int spot_id = latestParkingRecord.getSpot_id();
                service1.occupySpot(spot_id);

            }

        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        req.getRequestDispatcher("/main/admin/adminMain.jsp").forward(req, resp);
    }
}



