package de.hft.geotime.repositories;

import de.hft.geotime.entities.TimeRecord;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.PagingAndSortingRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
import org.springframework.data.rest.core.annotation.RestResource;
import org.springframework.format.annotation.DateTimeFormat;

import java.time.LocalDateTime;

@RepositoryRestResource(
        path = "records",
        itemResourceRel = "records",
        collectionResourceRel = "records"
)
public interface RecordRepository extends PagingAndSortingRepository<TimeRecord, Long> {

    @RestResource(rel = "allBetween", path = "allBetween")
    Page<TimeRecord> findAllByStartdateBetween(
            @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime start,
            @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime end,
            Pageable pageable
    );

    @RestResource(rel = "allBetweenAndUser", path = "allBetweenAndUser")
    Page<TimeRecord> findAllByStartdateBetweenAndAccount_User_Username(
            @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime start,
            @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime end,
            String username,
            Pageable pageable
    );

    @RestResource(rel = "allForUser", path = "allForUser")
    Page<TimeRecord> findAllByAccount_User_Username(String username, Pageable pageable);

    @RestResource(rel = "allForUserAndAccount", path = "allForUserAndAccount")
    Page<TimeRecord> findAllByAccount_User_UsernameAndAccount_Name(String username, String account, Pageable pageable);

    @RestResource(rel = "allFrom", path = "allFrom")
    Page<TimeRecord> findAllByStartdateGreaterThanEqual(
            @DateTimeFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss") LocalDateTime date,
            Pageable pageable
    );

    @Query("SELECT record from TimeRecord record where record.account.user.username = :#{principal} AND record.enddate > current_date")
    Page<TimeRecord> today(Pageable pageable);

    @RestResource(rel = "openEntries", path = "openEntries")
    Page<TimeRecord> findAllByEnddateIsNull(Pageable pageable);

}
