package ru.sweetbread.unn.db

import android.util.Log
import androidx.room.ColumnInfo
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Entity
import androidx.room.Insert
import androidx.room.PrimaryKey
import androidx.room.Query
import ru.sweetbread.unn.AvatarSet
import ru.sweetbread.unn.Type
import ru.sweetbread.unn.User
import ru.sweetbread.unn.ui.layout.db
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter

@Entity
data class UserDB(
    @PrimaryKey val userId: Int,
    @ColumnInfo val unnId: Int?,
    @ColumnInfo val bitrixId: Int,
    @ColumnInfo val type: Type,
    @ColumnInfo val email: String,
    @ColumnInfo val nameRu: String,
    @ColumnInfo val nameEn: String,
    @ColumnInfo val isMale: Boolean,
    @ColumnInfo val birthday: String,
    @ColumnInfo val origAvatar: String,
    @ColumnInfo val thumbAvatar: String,
    @ColumnInfo val smallAvatar: String,
    @ColumnInfo val expiredAt: String
)

@Dao
interface UserDao {
    @Query("SELECT * FROM userDB WHERE bitrixId = :bitrixId LIMIT 1")
    fun getUserByBitrix(bitrixId: Int): UserDB?

    @Insert
    fun insert(user: UserDB)

    @Delete
    fun delete(user: UserDB)
}


fun cacheUser(user: User) {
    try {
        db.userDao().insert(
            UserDB(
                user.userId,
                user.unnId,
                user.bitrixId,
                user.type,
                user.email,
                user.nameRu,
                user.nameEn,
                user.isMale,
                user.birthday.format(DateTimeFormatter.ISO_LOCAL_DATE),
                user.avatar.original,
                user.avatar.thumbnail,
                user.avatar.small,
                LocalDateTime.now().plusDays(1).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME)
            )
        )
    } catch (_: android.database.sqlite.SQLiteConstraintException) {
    }
}

fun loadUserByBitrixId(bitrixId: Int): User? {
    val user = db.userDao().getUserByBitrix(bitrixId)
    Log.d("UserDB", user?.nameEn ?: "None")
    if (user == null) return null
    if (LocalDateTime.parse(
            user.expiredAt,
            DateTimeFormatter.ISO_LOCAL_DATE_TIME
        ) < LocalDateTime.now()
    ) {
        db.userDao().delete(user)
        return null
    } else {
        return User(
            user.unnId,
            user.bitrixId,
            user.userId,
            user.type,
            user.email,
            user.nameRu,
            user.nameEn,
            user.isMale,
            LocalDate.parse(user.birthday, DateTimeFormatter.ISO_LOCAL_DATE),
            AvatarSet(
                user.origAvatar,
                user.thumbAvatar,
                user.smallAvatar
            )
        )
    }
}