package es.verdnatura.presentation.base

import android.content.Context
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.Settings
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.annotation.LayoutRes
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import androidx.fragment.app.Fragment
import androidx.room.Room
import es.verdnatura.MobileApplication
import es.verdnatura.R
import es.verdnatura.databinding.ToolbarFragmentBinding
import es.verdnatura.db.DeliveryDatabase
import es.verdnatura.presentation.view.feature.main.activity.MainActivity
import org.koin.androidx.viewmodel.ext.android.viewModel
import kotlin.reflect.KClass

abstract class BaseFragment<T : ViewDataBinding, V : BaseViewModel>(
    viewModelClass: KClass<V>
) : Fragment() {
    protected lateinit var mobileApplication: MobileApplication
    protected val viewModel: V by viewModel(viewModelClass)
    protected lateinit var binding: T
    protected lateinit var ma: MainActivity

    override fun onAttach(context: Context) {
        super.onAttach(context)

        if ((requireActivity().componentName).toString().contains("MainActivity")) {

            ma = activity as MainActivity
        }
        mobileApplication = requireActivity().application as MobileApplication
    }

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

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initDataBinding()
        getBundleArguments()
        observeViewModel()
        init()

    }

    @LayoutRes
    abstract fun getLayoutId(): Int
    open fun init() {}
    open fun observeViewModel() {}
    open fun getBundleArguments() {}
    open fun addBindingVariables() {}

    private fun initDataBinding() {
        binding = DataBindingUtil.bind<T>(requireView())!!
        binding.lifecycleOwner = viewLifecycleOwner
        binding.setVariable(BR.viewModel, this@BaseFragment.viewModel)
        lifecycle.addObserver(this@BaseFragment.viewModel)
        addBindingVariables()
    }

    fun textScanned_filterDouble(textScanned: String): String {

        if (textScanned.length > 13) {
            var size = textScanned.length
            if (textScanned.substring((size / 2), size) == textScanned.substring(0, size / 2)
            ) {
                return textScanned.substring(0, size / 2)

            }

        }
        return textScanned

    }

    fun getTooltip(image: Int): String {

        return when (image) {
            //itemCard
            R.drawable.ic_autorenew_black_24dp -> {
                getString(R.string.reloadItemData)
            }

            R.drawable.ic_history_black_24dp -> getString(R.string.showHistoricalItem)
            //presacador
            R.drawable.ic_local_parking_black_24dp -> getString(R.string.allowParking)
            //collection
            R.drawable.ic_print_black_24dp -> getString(R.string.printTicket)
            R.drawable.ic_playlist_add_black_24dp -> getString(R.string.addItem)
            R.drawable.ic_worker -> getString(R.string.showFacePicker)
            R.drawable.car -> getString(R.string.allowSelectVehicle)
            R.drawable.car_off -> getString(R.string.allowTakeoffVehicle)
            //REPETIDO:R.drawable.ic_history_black_24dp->"Realiza llamada al sacador"
            //sacador
            R.drawable.ic_add_black_24dp -> getString(R.string.newCollection)
            //REPETIDO: R.drawable.car->"Permite coger vehículo"
            //ubicador:
            //REPETIDO: R.drawable.ic_add_black_24dp->"Genera colección para sacar"
            //REPETIDO: ic_autorenew_black_24dp
            //historico articulo
            R.drawable.ic_transaction -> getString(R.string.showFilter)
            R.drawable.alpha_f_circle_outline -> getString(R.string.showFaults)
            R.drawable.alpha_b_circle_outline -> getString(R.string.showTrash)
            R.drawable.filter_outline -> getString(R.string.filterFlower)
            R.drawable.ic_mode_edit_black_24dp -> getString(R.string.allowChangeShelving)
            R.drawable.ic_delete_forever_black_24dp -> getString(R.string.deleteAllitems)
            R.drawable.ic_flash_auto_black_24dp -> getString(R.string.allowAutomaticAddItem)
            R.drawable.ic_logo_salix -> getString(R.string.accessSalix)
            R.drawable.ic_eye_ui -> getString(R.string.icViewCollection)
            R.drawable.ic_collection -> getString(R.string.icViewCollection)
            R.drawable.ic_ubicator_check -> getString(R.string.checkerUbication)
            R.drawable.ic_delivery_truck -> getString(R.string.loadRoute)
            R.drawable.ic_confirm -> getString(R.string.confirmDescription)
            R.drawable.camion -> getString(R.string.openLoadingConsignee)
            R.drawable.exit -> getString(R.string.exitScreen)
            R.drawable.ic_image_upload -> getString(R.string.messageUpload)
            R.drawable.expedition_find -> getString(R.string.showLogExpedition)
            R.drawable.ic_info_refresh -> getString(R.string.udpateRoutes)
            R.drawable.ic_info_delivery -> getString(R.string.info)
            R.drawable.ic_filter_inventory -> getString(R.string.filterNoReview)
            R.drawable.ic_remove_checks -> getString(R.string.resetReviewItems)
            R.drawable.ic_eye_inventory -> getString(R.string.inventoryShowParking)
            R.drawable.ic_sort -> getString(R.string.sortRouteSalix)
            R.drawable.ic_sign_ticket -> getString(R.string.signed)
            R.drawable.ic_send -> getString(R.string.sendDriverRoute)
            R.drawable.ic_add_multiple -> getString(R.string.addItemMultipleShelvings)
            else -> {
                ""
            }
        }

    }

    fun hideBackButton(tool: ToolbarFragmentBinding) {
        tool.backButton.visibility = View.INVISIBLE
    }

    fun getInfoVersionNameApp(): String {
        val manager: PackageManager = requireContext().packageManager
        val info: PackageInfo = manager.getPackageInfo(requireContext().packageName, 0)
        mobileApplication.versionName = info.versionName
        return info.versionName
    }

    fun getDevicePDA(): Int? {
        return try {
            Settings.Global.getString(
                mobileApplication.contentResolver, Settings.Global.DEVICE_NAME
            ).toInt()
        } catch (ex: Exception) {
            null
        }

    }

}

fun database(myContext: Context): DeliveryDatabase {
    return Room.databaseBuilder(
        myContext,
        DeliveryDatabase::class.java, "expediciones.db"
    ).build()
}


