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

import com.ys.bdtp.adm.mvvm.model.Data
import com.ys.bdtp.adm.mvvm.model.db.AdmDatabase
import com.ys.bdtp.adm.mvvm.model.db.entity.UserEntity
import com.ys.bdtp.adm.mvvm.model.db.entity.task.ProjectEntity
import com.ys.bdtp.adm.mvvm.model.nt.Api
import com.ys.bdtp.adm.mvvm.model.toStateFlow
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.withContext

/**
 * TaskRepository
 */
class TaskRepository(private val api: Api, private val db: AdmDatabase) {
    /**
     * 获取项目实例
     *
     * @author bai
     * @param id 项目id
     */
    suspend fun getProject(id: String): ProjectEntity {
        return withContext(Dispatchers.IO) {
            db.projectDao().getProjectById(id)
        }
    }

    /**
     * 获取当前登录用户
     */
    fun getUser(): Flow<Data<UserEntity?>> {
        return db.userDao().getUser().toStateFlow()
    }

    suspend fun logout() {
        withContext(Dispatchers.IO) {
            db.userDao().getUser().collect {
                it?.let {
                    it.state = 0
                    db.userDao().updUser(it)
                }
            }
        }
    }
}