package io.delphiplatform.api.integration.util;

import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;

import io.delphiplatform.api.util.DateUtils;
import io.delphiplatform.api.util.service.CurrentDateService;
import lombok.Setter;

@Primary
@Service
@Setter
public class MockCurrentDateService implements CurrentDateService {

    private static MockCurrentDateService instance;

    private LocalDateTime mockCurrentDateTime;

    public MockCurrentDateService() {
        if (MockCurrentDateService.instance != null) {
            throw new IllegalStateException("MockCurrentDateService instance already exists");
        }
        MockCurrentDateService.instance = this;
    }

    public static void setMockDateTime(LocalDateTime mockDateTime) {
        //for Spring-based integration tests - instance will be created by Spring
        //for unit tests - it will be created here at 1st call
        if (MockCurrentDateService.instance == null) {
            new MockCurrentDateService();
            new DateUtils(MockCurrentDateService.instance);
        }

        MockCurrentDateService.instance.setMockCurrentDateTime(mockDateTime);
    }

    @Override
    public LocalDate getCurrentDate() {
        return getCurrentDateTime().toLocalDate();
    }

    @Override
    public LocalDateTime getCurrentDateTime() {
        if (mockCurrentDateTime == null) {
            throw new IllegalStateException("mock date is not set");
        }

        return mockCurrentDateTime;
    }
}