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

import android.util.Log
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.Fail
import com.ys.bdtp.adm.mvvm.model.nt.request
import com.ys.bdtp.adm.mvvm.model.vo.request.Login
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * LoginRepository
 *
 * @author bai
 *
 * @param api
 */
class LoginRepository(private val api: Api, private val db: AdmDatabase) {

    /**
     * 登录
     */
    suspend fun login(login: Login): Response<String> {
        return withContext(Dispatchers.IO) {
            request {
                api.login(login)
            }
        }
    }

    /**
     * 获取账号信息
     */
    suspend fun requestAccount(password: String, success: () -> Unit, failure: (Fail) -> Unit) {
        request(
            request = { api.getAccount() },
            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 users = db.userDao().getUsers().onEach { u -> u.state = 0 }.toMutableList()
                users.add(user)
                db.userDao().insUsers(users)
                account.projects.forEach { it.userId = user.id }
                db.projectDao().insProjects(account.projects)
                success()
                Log.d("requestAccount", "login requestAccount success")
            },
            failure = { fail ->
                failure(fail)
                Log.d("requestAccount", "login requestAccount failure : $fail")
            }
        )
    }

}