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.fdc.model.Nozzle
import com.wayne.www.waynelib.fdc.model.Pump
import com.wayne.www.waynelib.listener.OnDropDownMenuClickListener
import com.wayne.www.waynelib.ui.view.NozzleGridView
import com.wayne.www.waynelib.ui.view.PumpView
import com.wayne.www.waynelib.common.Tuple
import org.slf4j.LoggerFactory
import java.util.ArrayList
import java.util.concurrent.locks.ReentrantLock

/**
 * Created by Justin on 5/8/2018.
 */
class NozzlesGridViewAdapter : BaseAdapter {
    private val fileLogger = LoggerFactory.getLogger(PumpView::class.java)
    private val LOG_TAG = "NozzlesGridViewAdapter"
    private var context: Context? = null
    private var pumps: MutableList<Pump>? = mutableListOf()
    private var nozzles: MutableList<Nozzle>? = mutableListOf()
    private var nozzleList = listOf<String>()
    private var OnDropDownMenuClickListener: OnDropDownMenuClickListener? = null
    private val lock = ReentrantLock()
    private var nozzleViews: MutableList<NozzleGridView>? = mutableListOf()

    constructor(context: Context, pumps: MutableList<Pump>, nozzleList: List<String>, gridView: GridView, listener: OnDropDownMenuClickListener) {
        this.context = context
        this.pumps = pumps
        this.nozzleList = nozzleList
        this.OnDropDownMenuClickListener = listener
        val menus = ArrayList<Tuple<String, Int>>()
        var i = 0
        for (p in pumps) {
            for (n in p.nozzles) {
                if (nozzles!!.size < nozzleList.size) {
                    nozzles!!.add(n)
                    val nozzleName = nozzleList[i++]
                    var nozzleGridView = NozzleGridView(context, menus, nozzleList.size, nozzleName, gridView)
                    nozzleGridView.bindNozzle(n)
                    nozzleGridView.addOnOnDropDownMenuClickListener(this.OnDropDownMenuClickListener)
                    nozzleViews!!.add(nozzleGridView)
                } else {
                    break
                }
            }
        }
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        fileLogger.debug("Null Binding nozzle model with PumpNo: " + this.nozzles!!.get(position).NozzleNo + " to a NozzleGridView at gridView position: " + position)
        if (convertView == null) {
            return this.nozzleViews?.get(position) as View
        } else
            return convertView
    }

    override fun getItem(position: Int): Any {
        return this.nozzles!!.get(position)
    }

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

    override fun getCount(): Int {
        return if (this.nozzles == null) 0 else this.nozzles!!.size
    }
}