package rasel.lunar.launcher.utils

import android.content.ContentResolver
import android.net.Uri
import android.provider.ContactsContract
import android.provider.ContactsContract.PhoneLookup

import java.util.Calendar
import java.util.Date

fun before30Min(date: Date): Long {
    val cal: Calendar = Calendar.getInstance()
    cal.setTime(date)
    cal.add(Calendar.MINUTE, -30)
    return cal.timeInMillis
}

fun beforeDay(date: Date?, day: Int): Long {
     val cal: Calendar = Calendar.getInstance()
    cal.setTime(date)
    cal.add(Calendar.DAY_OF_YEAR, Math.abs(day) * -1)
    return cal.timeInMillis
}

fun make0H(date: Date?): Long {
    val cal: Calendar = Calendar.getInstance()
    cal.setTime(date)
    cal.set(Calendar.HOUR, 1)
    return cal.timeInMillis
}

fun afterDay(date: Date?, day: Int): Long {
    val cal: Calendar = Calendar.getInstance()
    cal.setTime(date)
    cal.add(Calendar.DAY_OF_YEAR, Math.abs(day) * 1)
    return cal.timeInMillis
}



fun getContactName(contentResolver: ContentResolver, phoneNumber: String?): String? {
    var contactName: String? = null
    if (phoneNumber != null && phoneNumber.length > 0) {
        val cr = contentResolver
        val uri = Uri.withAppendedPath(ContactsContract.PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber))
        val cursor =
            cr.query(uri, arrayOf(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME), null, null, null)
                ?: return null
        if (cursor.moveToFirst()) {
            contactName = cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME))
        }

        if (cursor != null && !cursor.isClosed) {
            cursor.close()
        }
    }
    return contactName
}

fun getContactId(contentResolver: ContentResolver, phoneNumber: String?): String? {
    val cr = contentResolver
    val uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phoneNumber))
    val cursor =
        cr.query(uri, arrayOf(PhoneLookup._ID), null, null, null)
            ?: return null
    var contactName: String? = null
    if (cursor.moveToFirst()) {
        contactName = cursor.getString(cursor.getColumnIndexOrThrow(PhoneLookup._ID))
    }

    if (cursor != null && !cursor.isClosed) {
        cursor.close()
    }

    return contactName
}









