package com.example.what_the_fantasy.data.services

import android.annotation.SuppressLint
import com.example.what_the_fantasy.data.local.UserStub.users
import com.example.what_the_fantasy.data.model.User
import com.example.what_the_fantasy.logs.LogsUsers
import com.example.what_the_fantasy.data.local.FavoriteStub.favorites
import com.example.what_the_fantasy.data.local.ImageStub.allImages
import com.example.what_the_fantasy.data.local.QuoteStub.quotes
import com.example.what_the_fantasy.data.model.Favorite
import com.example.what_the_fantasy.data.local.CommentStub.comments
import com.example.what_the_fantasy.data.model.Comment
import com.example.what_the_fantasy.data.model.Quote
import com.example.what_the_fantasy.data.model.SrcLanguage
import java.time.LocalDate

class ServicesStub : IServices {
    val logsUser = LogsUsers() //gestion des logs pour les utilisateurs


    override fun validLogin(username : String,
                            passwd : String,
                            navController: (Int) -> Unit,
                            initialierCurrentUser : (Int) ->Unit): Boolean{

        users.forEachIndexed { index, user ->
            val hashPassWd = hashPassword(passwd)
            if (user.username == username && user.password == hashPassWd) {
                initialierCurrentUser(index)
                navController(index)
                logsUser.logInformationUserConnect(user, "UserConnect")
                return true
            }
        }
        return false
    }


    override fun EditUsername(username: String, index : Int) : Boolean{
        val user = getUserById(index)

        if(!isUsernameExist(username)){
            user?.username = username
            return true
        }

        //Afficher tous les users
        logsUser.logDebugUserEmail(user, "UsernameUpdate")
        return false
    }

    override fun EditEmail(email: String,index : Int) : Boolean {
        val user = getUserById(index)

        if(!isEmailExist(email)){
            user?.email = email
            return true
        }
        //Afficher tous les users
        logsUser.logDebugAllUsers(getAllUsers(), "EmailUpdate")
        return false
    }

    override fun EditPasswd(passwd: String,index : Int) {
        val user = getUserById(index)
        val passwordhash = hashPassword(passwd)
        user?.password = passwordhash

        //Afficher tous les users en log
        logsUser.logDebugAllUsers(getAllUsers(), "PasswordUpdate")
    }

    override fun EditImage(imageURL: String,index : Int) {
        TODO("Not yet implemented")
    }

    override fun ChangeLangage(index : Int) : SrcLanguage{
        if(getAllUsers()[index].langage == SrcLanguage.vo){
            getAllUsers()[index].langage = SrcLanguage.vf
        }
        else{
            getAllUsers()[index].langage = SrcLanguage.vo
        }

        logsUser.logDebugUserLangage(getAllUsers()[index], "ChangeLangue")
        return getAllUsers()[index].langage
    }

    override fun AddFav(userId: Int, QuoteId: Int) {
        return
    }

    override fun SupFav(userId: Int, QuoteId: Int) {
        return
    }

    override fun AddComment(content: String) {
        return
        TODO("Not yet implemented")
        //comments.add(Comment(content = content,))
    }


    override fun CreateUser(username: String, email: String, passwd: String) : Boolean {
        val date =dateDuJour()
        val passwordhash = hashPassword(passwd)
        val services = ServicesStub()

        val userStub = services.getAllUsers()
        val nbUser = userStub.size

        if(!isUsernameExist(username) && !isEmailExist(email)){
            val user = User(nbUser,username, email, date,randomImage(), passwordhash, SrcLanguage.vo)
            users.add(user)//ajout au stub

            //Afficher tous les users
            logsUser.logDebugAllUsers(users, "CreateUser")
            return true
        }
        return false
    }

    override fun getFavorite(user: User): List<Quote> {
        val favorite = favorites
        return favorite[0].quote
    }

    override fun getAllFavorite(): List<Favorite> = favorites
    override fun getAllQuote(): List<Quote> = quotes
    override fun getAllUsers(): List<User> = users

    override fun getComment(quoteId: Int): List<Comment> = comments

    override fun getUserById(id: Int): User? {
        return (users.find { it.id == id })
    }

    override fun SearchQuote(quote: String) {
        TODO("Not yet implemented")
    }

    override fun getQuote(id: Int): Quote? {
        return (quotes.find { it.id == id })
    }

    override fun getSomeQuotes(nb: Int, page: Int): MutableList<Quote> {
        val fromIndex = (page - 1) * nb
        val toIndex = minOf(page * nb, quotes.size)

        if (fromIndex >= quotes.size) return mutableListOf()

        return quotes.subList(fromIndex, toIndex).toMutableList()
    }
    override fun isFavorite(id: Int, user: User): Boolean {
        val quote = getFavorite(user)
        return quote.find{ it.id == id } != null
    }




    //------------------------------------------------------
    @SuppressLint("NewApi")
    fun dateDuJour(): String {
        val date = LocalDate.now()
        return date.toString()
    }

    fun randomImage() : String{
        val sizeList = allImages.size
        val randomNb = (0..sizeList).random()
        allImages.forEach{image ->
            if(image.id == randomNb){
                return image.url
            }

        }
        return allImages[0].url
    }

    fun isUsernameExist(username : String) : Boolean{
        val userStub = getAllUsers()
        for (user in userStub) {
            if (user.username == username) {
                return true
            }
        }
        return false
    }

    fun isEmailExist(email : String) : Boolean{
        val userStub = getAllUsers()
        for (user in userStub) {
            if (user.email == email) {
                return true
            }
        }
        return false
    }

    override fun search(type : String ,search:String ,indexCount: Int): List<Quote> {
        return (getAllQuote().filter {
            when (type) {
                "personnage" -> {
                    it.character.uppercase().contains(search.uppercase())
                }

                "titre" -> {
                    it.source.uppercase().contains(search.uppercase())
                }

                else -> {
                    it.content.uppercase().contains(search.uppercase())
                }
            }
        }.take(indexCount))
    }
}