package bums.lunatic.launcher.feeds

import android.content.DialogInterface
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.FragmentManager
import bums.lunatic.launcher.apps.DismissCalback
import bums.lunatic.launcher.databinding.FeedsResultMenuBinding
import bums.lunatic.launcher.model.LocationLog
import bums.lunatic.launcher.utils.BLog
import bums.lunatic.launcher.workers.WorkersDb
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.bottomsheet.BottomSheetDialogFragment
import io.realm.kotlin.ext.query
import io.realm.kotlin.query.Sort
import java.text.SimpleDateFormat
import java.util.Date

internal class FeedsResult : BottomSheetDialogFragment() {

    private lateinit var binding: FeedsResultMenuBinding
    private lateinit var searchWord: String
    private lateinit var packageManager: PackageManager
    private lateinit var appInfo: ApplicationInfo

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
        binding = FeedsResultMenuBinding.inflate(inflater, container, false)

        /* get package name from fragment's tag */
        searchWord = tag.toString()
        WorkersDb.getRealm().query<LocationLog>().sort("time", Sort.DESCENDING).find()?.let {
            if (it.size > 0) {
                binding.logs.text = it.map {
                    BLog.LOGE("LocLog >> ${it.toString()}")
                    SimpleDateFormat("yyyy/MM/dd-HH:mm:ss").format(Date(it.time)).plus("\n").plus(it.mAddressLines.joinToString(" ,\n"))
                }.joinToString( ",\n")
            }
        }
        return binding.root
    }

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


    }


    var mDismissCalback : DismissCalback? = null

    fun show(manager: FragmentManager, tag: String?, dismissCalback : DismissCalback?) {
        this.mDismissCalback = dismissCalback
        this.show(manager, tag)
    }

    override fun show(manager: FragmentManager, tag: String?) {
        super.show(manager, tag)
    }

    override fun dismiss() {
        BLog.LOGE("dismiss()")
        mDismissCalback?.invoke()
        super.dismiss()
    }

    override fun onDismiss(dialog: DialogInterface) {
        BLog.LOGE("onDismiss(dialog: DialogInterface)")
        mDismissCalback?.invoke()
        super.onDismiss(dialog)
    }
}