package com.wayne.www.waynelib.ui.adapter

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.GridView
import com.wayne.www.waynelib.entity.ShellTrxStatus
import com.wayne.www.waynelib.listener.OnItemViewButtonClickListener
import com.wayne.www.waynelib.ui.view.ShellNozzleGridView
import org.slf4j.LoggerFactory

class ShellTrxNozzleGridViewAdapter : BaseAdapter {
    private val fileLogger = LoggerFactory.getLogger(ShellTrxNozzleGridViewAdapter::class.java)
    private val LOG_TAG = "ShellTrxNozzleGridViewAdapter"
    private var context: Context? = null
    private var onItemViewButtonClickListener: OnItemViewButtonClickListener? = null
    private var nozzleList: List<String> = mutableListOf()
    private var nozzleIds: List<String> = mutableListOf()
    private var nozzleViews: MutableList<ShellNozzleGridView>? = mutableListOf()
    private var transactionStatus: HashMap<String, List<ShellTrxStatus?>>? = null


    constructor(baseContext: Context?, nozzleList: List<String>, idList: List<String>, gridView: GridView, onItemViewButtonClickListener: OnItemViewButtonClickListener? ) {
        this.context = baseContext
        this.nozzleList = nozzleList
        this.nozzleIds = idList
        this.onItemViewButtonClickListener = onItemViewButtonClickListener
        if (nozzleList.size == idList.size) {
            for (i in 0 until this.nozzleList.size){
                val nozzleName = this.nozzleList[i]
                val nozzleId = this.nozzleIds[i]
                var nozzleGridView = ShellNozzleGridView(baseContext!!, nozzleList.size, nozzleName, gridView, nozzleId)
                nozzleGridView.addOnItemViewButtonClickListener(this.onItemViewButtonClickListener)
                nozzleViews!!.add(nozzleGridView)
            }
        } else {
            fileLogger.error("nozzleList.size != idList.size !!!")
        }
    }

    fun setData(data: HashMap<String, List<ShellTrxStatus?>>?) {
        this.transactionStatus = data
        this.nozzleViews?.forEach {
            if (this.transactionStatus?.contains(it.getNozzleId())!!) {
                val trx = this.transactionStatus?.get(it.getNozzleId())
                it.setData(trx)
            }
        }
    }

    override fun getView(position: Int, p1: View?, p2: ViewGroup?): View {
        return nozzleViews?.get(position) as View
    }

    override fun getItem(position: Int): Any {
        return nozzleViews?.get(position)!!
    }

    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getCount(): Int {
        return nozzleViews?.size!!
    }

    fun clearListeners() {
        for (nozzleView in nozzleViews!!) {
            nozzleView.removeViewButtonClickListener()
        }
        nozzleViews?.clear()
    }
}