package hanson.xyz.vpnhotspotmod.manage

import android.content.Intent
import android.view.View
import androidx.recyclerview.widget.RecyclerView
import hanson.xyz.vpnhotspotmod.R
import hanson.xyz.vpnhotspotmod.TetheringService
import hanson.xyz.vpnhotspotmod.databinding.ListitemInterfaceBinding
import hanson.xyz.vpnhotspotmod.net.TetherType
import hanson.xyz.vpnhotspotmod.util.formatAddresses
import java.util.*

class InterfaceManager(private val parent: TetheringFragment, val iface: String) : Manager() {
    class ViewHolder(val binding: ListitemInterfaceBinding) : RecyclerView.ViewHolder(binding.root),
            View.OnClickListener {
        init {
            itemView.setOnClickListener(this)
        }

        lateinit var iface: String

        override fun onClick(view: View) {
            val context = itemView.context
            val data = binding.data as Data
            if (data.active) context.startService(Intent(context, TetheringService::class.java)
                    .putExtra(TetheringService.EXTRA_REMOVE_INTERFACE, iface))
            else context.startForegroundService(Intent(context, TetheringService::class.java)
                    .putExtra(TetheringService.EXTRA_ADD_INTERFACES, arrayOf(iface)))
        }
    }
    private inner class Data : hanson.xyz.vpnhotspotmod.manage.Data() {
        override val icon get() = TetherType.ofInterface(iface).icon
        override val title get() = if (parent.binder?.monitored(iface) == true) {
//        override val title get() = if (true) {
            parent.getString(R.string.tethering_state_monitored, iface)
        } else iface
        override val text get() = addresses
        override val active get() = parent.binder?.isActive(iface) == true
    }

    private val addresses = parent.ifaceLookup[iface] ?.formatAddresses(parent.binder?.isInactive(iface) == true) ?: ""
    override val type get() = VIEW_TYPE_INTERFACE
    private val data = Data()

    override fun bindTo(viewHolder: RecyclerView.ViewHolder) {
        viewHolder as ViewHolder
        viewHolder.binding.data = data
        viewHolder.iface = iface
    }

    override fun isSameItemAs(other: Manager) = when (other) {
        is InterfaceManager -> iface == other.iface
        else -> false
    }

    override fun equals(other: Any?): Boolean {
        if (this === other) return true
        if (javaClass != other?.javaClass) return false
        other as InterfaceManager
        if (iface != other.iface) return false
        if (addresses != other.addresses) return false
        return true
    }
    override fun hashCode(): Int = Objects.hash(iface, addresses)
}
