package rasel.lunar.launcher.workers

import android.content.Context
import android.provider.ContactsContract
import androidx.work.WorkerParameters
import io.realm.kotlin.ext.query
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.apps.SimpleContact

class ContactInfoGetter : BaseGetter {
    companion object {
        val TAG = "ContactInfoGetter"
    }
    constructor(context: Context, workerParams: WorkerParameters) : super(context, workerParams) {

    }
    override fun realWork(): Result {
        val phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
        val projection = arrayOf(
            ContactsContract.CommonDataKinds.Phone.CONTACT_ID,
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
        )

        try {
            val cursor = lActivity?.contentResolver?.query(phoneUri, projection, null, null, null)
            if (cursor != null) {
                while (cursor.moveToNext()) {
                    val idx =cursor.getColumnIndex(projection[0])
                    val nameIndex = cursor.getColumnIndex(projection[1])
                    val numberIndex = cursor.getColumnIndex(projection[2])
                    var contactId = cursor.getString(idx)
                    val name = cursor.getString(nameIndex)
                    var number = cursor.getString(numberIndex)
                    number = number.replace("-", "")
                    if (name?.length ?: 0 > 0 && number?.length ?: 0 > 0) {
                        if (WorkersDb.getRealm().query<SimpleContact>("id == $0", contactId).find().size == 0) {
                            WorkersDb.update(SimpleContact(contactId,name,number))
                        }
                    }
                }
            }
            // 데이터 계열은 반드시 닫아줘야 한다.
            cursor?.close()
        } catch ( e : Exception) {
            e.printStackTrace()
        }
        return Result.success()
    }
}