package com.ys.bdtp.adm.mvvm.vm.project

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ys.bdtp.adm.mvvm.model.nt.Fail
import com.ys.bdtp.adm.mvvm.model.nt.FailureResponse
import com.ys.bdtp.adm.mvvm.model.nt.Response
import com.ys.bdtp.adm.mvvm.model.nt.SuccessResponse
import com.ys.bdtp.adm.mvvm.model.db.entity.task.ProjectEntity
import com.ys.bdtp.adm.mvvm.model.db.entity.UserEntity
import com.ys.bdtp.adm.mvvm.model.db.entity.relation.UserWithProjects
import com.ys.bdtp.adm.mvvm.model.vo.request.Account
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.SharingStarted.Companion.WhileSubscribed
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch

/**
 * ProjectViewModel
 *
 * @author bai
 *
 * @param
 */
class ProjectViewModel(private val repo: ProjectRepository) : ViewModel() {

    /**
     * 获取项目信息
     */
    suspend fun getProjects(): List<ProjectEntity> {
        return repo.getProjects()
    }

    /**
     * 获取账号信息
     */
    suspend fun getAccount(success: (Account) -> Unit, failure: (Fail) -> Unit) {
        viewModelScope.launch {
            when (val response = repo.getAccount()) {
                is SuccessResponse -> {
                    success(response.data)
                }
                is FailureResponse -> {
                    failure(response.fail)
                }
            }
        }
    }

    /**
     * 获取账号信息
     */
    suspend fun getAccount(): Response<Account> {
        return repo.getAccount()
    }

    suspend fun setCurrentAccount(account: Account) {
        repo.setCurrentAccount(account)
    }

    /**
     * 获取用户与项目一对多关系
     */
    suspend fun getUserWithProjectsById(id: String): UserWithProjects {
        return repo.getUserWithProjectsById(id)
    }

    suspend fun currentUser(): UserEntity? {
        return repo.getCurrentUser()
    }

    suspend fun logout() {
        repo.logout()
    }

    val userFlow: StateFlow<UserEntity?> = repo.getUser().stateIn(
        scope = viewModelScope,
        started = WhileSubscribed(5000),
        initialValue = null
    )

}