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

import android.util.Log
import com.ys.bdtp.adm.mvvm.model.Data
import com.ys.bdtp.adm.mvvm.model.data
import com.ys.bdtp.adm.mvvm.model.nt.Response
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.nt.Api
import com.ys.bdtp.adm.mvvm.model.nt.request
import com.ys.bdtp.adm.mvvm.model.vo.request.Account
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.withContext

/**
 * 闪屏页数据仓库
 *
 * @author bai
 * @param api [Api]
 * @param db [AdmDatabase]
 */
class FlashRepository(private val api: Api, private val db: AdmDatabase) {

    /**
     * 获取当前登录用户
     */
    suspend fun currentUser(): UserEntity? {
        return withContext(Dispatchers.IO) {
            db.userDao().currentUser()
        }
    }

    suspend fun getAccount(): Response<Account> {
        return withContext(Dispatchers.IO) {
            request {
                api.getAccount()
            }
        }
    }

    /*suspend fun getUser(password: String): Flow<Data<UserEntity?>> {
        return data(
            fromDb = {
                db.userDao().getCurrentUser()
            },
            fromNt = {
                api.getAccount()
            },
            needNt = {
                true
            },
            success = { account ->
                val user = UserEntity(
                    password = password,
                    state = 1,
                    id = account.id,
                    account = account.account,
                    deptId = account.deptId,
                    email = account.email,
                    phone = account.phone,
                    name = account.name,
                )
                val userDao = db.userDao()
                val users = userDao.getUsers().onEach { u -> u.state = 0 }
                userDao.insUsers(users)
                userDao.insUser(user)
                account.projects.forEach { it.userId = user.id }
                db.projectDao().insProjects(account.projects)
                Log.d("FlashRepository", "FlashRepository getUser success")
            },
            failure = { fail ->
                Log.d("FlashRepository", "FlashRepository getUser failure: $fail")
            }
        )
    }
*/
}