package com.zaojiao.app.data.local.user

import android.util.Log
import androidx.datastore.core.DataStore
import com.zaojiao.app.data.local.UserPreferences
import com.zaojiao.app.data.local.copy
import com.zaojiao.app.data.model.UserModel
import kotlinx.coroutines.flow.map
import java.io.IOException
import javax.inject.Inject

class LocalUserData @Inject constructor(
    private val userPreferences: DataStore<UserPreferences>,
) {
    val user = userPreferences.data.map {
        if (!it.valid) null else UserModel(
            id = it.id,
            nickName = it.nickName,
            gender = it.gender,
            avatarUrl = it.avatarUrl,
            phone = it.phone,
            birthday = it.birthday,
            bindWx = it.bindWx,
            bindPhone = it.bindPhone,
        )
    }

    suspend fun updateUser(userModel: UserModel) {
        try {
            userPreferences.updateData {
                it.copy {
                    valid = true
                    id = userModel.id
                    nickName = userModel.nickName
                    gender = userModel.gender
                    avatarUrl = userModel.avatarUrl
                    if (userModel.phone != null) {
                        phone = userModel.phone!!
                    } else {
                        clearPhone()
                    }
                    if (userModel.birthday != null) {
                        birthday = userModel.birthday!!
                    } else {
                        clearBirthday()
                    }
                    bindWx = userModel.bindWx
                    bindPhone = userModel.bindPhone
                }
            }
        } catch (exception: IOException) {
            Log.e("LocalUserData", "updateUser: Failed....", exception)
        }
    }

    suspend fun updateBindWx(bind: Boolean) {
        try {
            userPreferences.updateData {
                it.copy {
                    if (it.valid) bindWx = if (bind) 1 else 0
                }
            }
        } catch (exception: IOException) {
            Log.e("LocalUserData", "updateUser: Failed....", exception)
        }
    }

    suspend fun updateBindPhone(bind: Boolean) {
        userPreferences.updateData {
            it.copy {
                if (it.valid) bindPhone = if (bind) 1 else 0
            }
        }
    }

    suspend fun deleteUser() {
        userPreferences.updateData {
            it.copy {
                valid = false
                clearId()
                clearNickName()
                clearGender()
                clearAvatarUrl()
                clearPhone()
                clearBirthday()
                clearBindWx()
                clearBindPhone()
            }
        }
    }
}