package com.pixelized.biblib.network.factory

import com.pixelized.biblib.model.user.DownloadedBooks
import com.pixelized.biblib.model.user.User
import com.pixelized.biblib.network.data.response.UserResponse
import com.pixelized.biblib.utils.exception.missingField
import java.text.DateFormat

class UserFactory constructor(
    private val parser: DateFormat,
) {
    fun fromUserResponseToUser(
        response: UserResponse
    ): User {
        fun error(name: String) = missingField("#fromUserResponseToUser()", name, response)

        val id = response.data?.id
        val created = response.data?.created?.let { parser.parse(it) }
        val updated = response.data?.updated?.let { parser.parse(it) }
        val username = response.data?.local?.username
        val firstname = response.data?.local?.firstname
        val lastname = response.data?.local?.lastname
        val amazonEmails = response.data?.local?.amazonEmails

        val downloadedBooks = response.data?.history?.downloadedBooks?.mapNotNull { book ->
            val bookId = book.id
            val date = book.date?.let { parser.parse(it) }
            val format = book.data?.data_format
            if (bookId != null && date != null && format != null) {
                DownloadedBooks(
                    bookId = bookId,
                    date = date,
                    format = format,
                )
            } else {
                null
            }
        }

        return User(
            id = id ?: throw error("id"),
            created = created ?: throw error("created"),
            updated = updated ?: throw error("updated"),
            username = username ?: throw error("username"),
            firstname = firstname,
            lastname = lastname,
            amazonEmails = amazonEmails ?: listOf(),
            downloadedBooks = downloadedBooks ?: listOf()
        )
    }
}