package dev.ksan.etfoglasiserver.controller;

import dev.ksan.etfoglasiserver.dto.EntryDTO;
import dev.ksan.etfoglasiserver.model.Entry;
import dev.ksan.etfoglasiserver.service.EntryService;
import java.util.List;
import java.util.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.ResponseStatusException;

@RestController
@RequestMapping("/api")
public class EntryController {
  @Autowired EntryService service;

  @GetMapping("/entries/{entryId}")
  public Entry getEntry(@PathVariable String entryId) {
    return service.getEntryById(entryId);
  }

  // TODO only for testing
  @PostMapping("/entries")
  public void addEntry(@RequestBody EntryDTO entry) {
    service.addEntry(entry);
  }


  @GetMapping("/groups")
  public List<String> getGroups() {
    return service.getAllGroups();
  }




  @GetMapping("/entries")
  public Page<Entry> getEntries(
          @RequestParam(required = false) String subjectId,
          @RequestParam(required = false) String groupName,
          @RequestParam(defaultValue = "0") int page
  ) {
//    UUID parsedSubjectId = subjectId != null ? UUID.fromString(subjectId) : null;

    UUID parsedSubjectId = null;
    if (subjectId != null) {
      try{
        parsedSubjectId = UUID.fromString(subjectId);
      }catch (IllegalArgumentException e){
        throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid subject ID");
      }
    }


    return service.getEntries(parsedSubjectId, groupName, page);
  }


//  @PutMapping("/entries")
//  public void updateEntry(@RequestBody EntryDTO entry) {
//    service.updateEntry(entry);
//  }

//  @DeleteMapping("/entries/{entryId}")
//  public void deleteEntry(@PathVariable String entryId) {
//    service.deleteEntry(entryId);
//  }
//
}
