package ru.fincode.tsudesk.feature.schedule.data.local

import ru.fincode.tsudesk.core.database.api.schedule.Constants.GROUP_PRE_KEY
import ru.fincode.tsudesk.core.database.api.schedule.Constants.TEACHER_PRE_KEY
import ru.fincode.tsudesk.core.database.api.schedule.LessonCacheEntity
import ru.fincode.tsudesk.core.database.api.schedule.ScheduleCacheEntity
import ru.fincode.tsudesk.feature.schedule.domain.model.LessonEntity
import ru.fincode.tsudesk.feature.schedule.domain.model.LessonType
import ru.fincode.tsudesk.feature.schedule.domain.model.ScheduleEntity


object ScheduleCacheKey {
    fun group(number: String) = "$GROUP_PRE_KEY$number"
    fun teacher(name: String) = "$TEACHER_PRE_KEY$name"
}


fun ScheduleEntity.toCache(
    key: String
): Pair<ScheduleCacheEntity, List<LessonCacheEntity>> {

    val scheduleCache = ScheduleCacheEntity(
        key = key,
        timestamp = timestamp
    )

    val lessonsCache = lessons.map { lesson ->
        LessonCacheEntity(
            scheduleKey = key,
            date = lesson.date,
            time = lesson.time,
            name = lesson.name,
            typeName = lesson.typeName,
            room = lesson.room,
            teacher = lesson.teacher,
            groupIds = lesson.groupIds,
            type = lesson.type.toString()
        )
    }

    return scheduleCache to lessonsCache
}

fun ScheduleCacheEntity.toDomain(
    lessons: List<LessonCacheEntity>
): ScheduleEntity =
    ScheduleEntity(
        lessons = lessons.map { it.toDomain() },
        timestamp = timestamp
    )

private fun LessonCacheEntity.toDomain(): LessonEntity =
    LessonEntity(
        date = date,
        time = time,
        name = name,
        typeName = typeName,
        room = room,
        teacher = teacher,
        groupIds = groupIds,
        type = LessonType.fromApi(type)
    )
