/*
 * Lunar Launcher
 * Copyright (C) 2022 Md Rasel Hossain
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package rasel.lunar.launcher.apps

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.provider.ContactsContract
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import io.realm.kotlin.ext.query
import rasel.lunar.launcher.LauncherActivity.Companion.lActivity
import rasel.lunar.launcher.databinding.ContactMenuBinding
import rasel.lunar.launcher.utils.BLog
import rasel.lunar.launcher.workers.WorkersDb
import java.text.SimpleDateFormat
import java.util.Date


internal class ContactMenu : BottomSheetDialogFragment() {

    private lateinit var binding: ContactMenuBinding
    private lateinit var contactId: String

    var contactName : String = ""
    var contactPhoneNumber : String = ""
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = ContactMenuBinding.inflate(inflater, container, false)

        /* get package name from fragment's tag */
        contactId = tag.toString()

        WorkersDb.getRealm().writeBlocking {
            if (contactId != null && contactId.length ?: 0 > 0) {
                val result = query<SimpleContact>().query("id == $0", contactId).find()
                if(result.size > 0){
                    var contact = result.first()
                    binding.totalTouch.text = "총 연락 횟수 : ".plus(contact.touchCount.toString())
                    binding.lastTouchDate.text = "마지막 연락 시간 : ".plus(SimpleDateFormat("yyyy-MM-dd HH:mm").format(Date(contact.lastedTouchDateTime)))

                }
            }
        }

        fun update() {
            WorkersDb.getRealm().writeBlocking {
                if (contactId != null && contactId.length ?: 0 > 0) {
                    val result = query<SimpleContact>().query("id == $0", contactId).find()
                    if(result.size > 0){
                        var contact = result.first()
                        contact.touchCount = contact.touchCount + 15
                    }
                }
            }
        }
        binding.totalTouch.setOnClickListener { update() }
        binding.lastTouchDate.setOnClickListener { update() }

        val resolver = lActivity!!.contentResolver
        val phoneUri = ContactsContract.CommonDataKinds.Phone.CONTENT_URI
        val projection = arrayOf(
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
            ContactsContract.CommonDataKinds.Phone.NUMBER,
        )

        BLog.LOGE("GetContact", "packageName ${contactId}")
       try {
           val cursor = resolver.query(phoneUri, projection, ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = " + contactId, null , null)
           if (cursor != null) {
               while (cursor.moveToNext()) {
                   val nameIndex = cursor.getColumnIndex(projection[0])
                   val numberIndex = cursor.getColumnIndex(projection[1])
                   contactName = cursor.getString(nameIndex)
                   var number = cursor.getString(numberIndex)
                   contactPhoneNumber = number.replace("-", "")
                   BLog.LOGE("GetContact", "이름 : $contactName 번호 : $contactPhoneNumber ")
               }
           }
           // 데이터 계열은 반드시 닫아줘야 한다.
           cursor!!.close()
       } catch ( e : Exception) {
           e.printStackTrace()
       }

        /* get application info */


        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (requireDialog() as BottomSheetDialog).dismissWithAnimation = true

        /* copy package name */
//        binding.appPackage.setOnClickListener {
//            copyToClipboard(requireContext(), packageName)
//        }
//
        appName()
        binding.detailedInfo.setOnClickListener { detailedInfo() }
        binding.call.setOnClickListener { callPhone() }
        binding.sms.setOnClickListener { sendSms() }
//        binding.activityBrowser.setOnClickListener { activityBrowser() }
//        binding.appStore.setOnClickListener { appStore() }
//        binding.appFreeform.setOnClickListener { freeform() }
//        binding.appInfo.setOnClickListener { appInfo() }
//        binding.appShare.setOnClickListener { share() }
//        binding.appUninstall.setOnClickListener { uninstall() }
    }



    private fun appName() {
        binding.appName.text = contactName
        binding.phoneNumber.text = contactPhoneNumber
    }


    private fun detailedInfo() {
        var intent = Intent(Intent.ACTION_VIEW);
        intent.setData(Uri.parse(ContactsContract.Contacts.CONTENT_URI.toString() + "/" + contactId));
        startActivity(intent);
    }

    private fun sendSms() {
        var intent = Intent(Intent.ACTION_SEND);
        intent.setData(Uri.parse("smsto:" + contactPhoneNumber));
        startActivity(intent);
    }
    private fun callPhone() {
        var intent = Intent(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + contactPhoneNumber));
        startActivity(intent);
    }



}
