package org.octopus.internal.repositories.impl

import org.octopus.internal.common.enums.EBusinessException
import org.octopus.internal.common.enums.EEntryType
import org.octopus.internal.common.exceptions.OctopusPlanningException
import org.octopus.internal.common.mappers.EntryMapper
import org.octopus.internal.common.models.Entry
import org.octopus.internal.db.EntryJpa
import org.octopus.internal.repositories.EntryRepository
import org.springframework.stereotype.Component
import java.time.Month
import java.util.*

@Component
class EntryRepositoryImpl(
    private val jpa: EntryJpa,
    private val mapper: EntryMapper
) : EntryRepository {

    override fun getById(id: Long): Entry {
        return mapper.toModel(
            jpa.findById(id).orElseThrow {
                OctopusPlanningException.create(
                    EBusinessException.ENTITY_WITH_ID_NOT_FOUND,
                    Entry::class.java.simpleName,
                    id
                )
            })
    }

    override fun createEntry(entry: Entry): Entry {
        return mapper.toModel(jpa.save(mapper.toEntity(entry)))
    }

    override fun getAllByType(type: EEntryType): MutableList<Entry> {
        return mapper.toModels(jpa.findAllByType(type))
    }

    override fun deleteById(id: Long): Boolean {
        jpa.deleteById(id)
        return true

    }

    override fun deleteAll(): Boolean {
        jpa.deleteAll()
        return true
    }

    override fun getAllRecurrentMonthlyToEndDate(endDate: Date): MutableList<Entry> {
        return mapper.toModels(
            jpa.findAllByFixedDateIsNullAndRecurrentIsTrueAndEndDateIsNotNullAndEndDateLessThanEqual(endDate)
        )
    }

    override fun getAllRecurrentOnSpecificMonths(months: List<Month>): MutableList<Entry> {
        return mapper.toModels(
            jpa.findAllByFixedDateIsNullAndRecurrentIsTrueAndRecurrentMonthsIn(months)
        )
    }

    override fun getAllRecurrentOnAllMonths(): MutableList<Entry> {
        return mapper.toModels(
            jpa.findAllByFixedDateIsNullAndRecurrentIsTrueAndRecurrentMonthsIn(Month.entries)
        )
    }

    override fun getAllFixedUpToEndDate(endDate: Date): MutableList<Entry> {
        return mapper.toModels(
            jpa.findAllByFixedDateIsNotNullAndFixedDateLessThanEqual(endDate)
        )
    }

}