package ru.mcs.tracker.ui.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import ru.mcs.tracker.ui.dto.LocationDto;
import ru.mcs.tracker.ui.service.LocationApiService;
import java.time.LocalDateTime;
import java.util.List;
@Controller
public class WebController {
private static final Logger logger = LoggerFactory.getLogger(WebController.class);
private final LocationApiService locationApiService;
public WebController(LocationApiService locationApiService) {
this.locationApiService = locationApiService;
logger.info("WebController initialized");
}
@GetMapping("/")
public String index(Model model) {
logger.info("Loading index page");
try {
List<String> deviceGuids = locationApiService.getDeviceGuids();
model.addAttribute("deviceGuids", deviceGuids);
logger.debug("Loaded {} device GUIDs", deviceGuids.size());
} catch (Exception e) {
logger.error("Error loading device GUIDs: {}", e.getMessage(), e);
model.addAttribute("error", "Unable to load device list");
}
return "index";
}
@GetMapping("/track")
public String track(
@RequestParam String deviceGuid,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end,
Model model) {
logger.info("Tracking device: {}", deviceGuid);
// Если даты не указаны, используем последние 24 часа
if (start == null) {
start = LocalDateTime.now().minusHours(24);
}
if (end == null) {
end = LocalDateTime.now();
}
try {
var locations = locationApiService.getLocations(deviceGuid, start, end);
model.addAttribute("locations", locations);
model.addAttribute("deviceGuid", deviceGuid);
model.addAttribute("start", start);
model.addAttribute("end", end);
logger.debug("Loaded {} locations for device {}", locations.size(), deviceGuid);
} catch (Exception e) {
logger.error("Error loading locations for device {}: {}", deviceGuid, e.getMessage(), e);
model.addAttribute("error", "Unable to load location data");
}
return "track";
}
@GetMapping("/track/{deviceGuid}/data")
@ResponseBody
public List<LocationDto> getTrackData(
@PathVariable String deviceGuid,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime start,
@RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) LocalDateTime end) {
return locationApiService.getLocations(deviceGuid, start, end);
}
}