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

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.ys.bdtp.adm.mvvm.model.Fail
import com.ys.bdtp.adm.mvvm.model.FailureResponse
import com.ys.bdtp.adm.mvvm.model.Response
import com.ys.bdtp.adm.mvvm.model.SuccessResponse
import com.ys.bdtp.adm.mvvm.model.db.entity.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.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()
    }
}