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

import android.content.Context
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import com.wayne.www.waynelib.fdc.model.FuelSaleTransaction
import com.wayne.www.waynelib.fdc.model.Nozzle
import com.wayne.www.waynelib.listener.OnItemViewButtonClickListener
import com.wayne.www.waynelib.ui.view.WayneTransactionStatusItemView

/**
 * Created by Justin on 4/13/2018.
 */
class WayneTransactionStatusAdapter : BaseAdapter {

    private var transactionStatus: List<FuelSaleTransaction?>? = null
    private var context: Context? = null
    private var nozzleList: MutableList<Nozzle>? = mutableListOf()
    private var onItemViewButtonClickListener: OnItemViewButtonClickListener? = null
    private var nozzleIdList: List<String?>? = null

    constructor(baseContext: Context?, trxList: List<FuelSaleTransaction?>, nozzleList: MutableList<Nozzle>?, nozzleIdList: List<String>, onItemViewButtonClickListener: OnItemViewButtonClickListener? ) {
        this.context = baseContext
        this.transactionStatus = trxList
        this.nozzleList = nozzleList
        this.nozzleIdList = nozzleIdList
        this.onItemViewButtonClickListener = onItemViewButtonClickListener
    }

    fun setData(data: List<FuelSaleTransaction?>?) {
        this.transactionStatus = data
    }

    override fun getView(position: Int, view: View?, viewGroup: ViewGroup?): View {
        val nozzle = findNozzleByFuelSaleTransaction(this.transactionStatus!!.get(position)!!)
        val nozzleName = findNozzleName(this.transactionStatus!!.get(position)!!)
        val v = WayneTransactionStatusItemView(this.context, this.transactionStatus!!.get(position)!!, nozzle, nozzleName, if (position == 0) true else false)
        v.addOnItemViewButtonClickListener(this.onItemViewButtonClickListener)
        return v
    }

    private fun findNozzleName(fuelSaleTransaction: FuelSaleTransaction): String? {
        for (i in nozzleList!!.indices) {
            if (fuelSaleTransaction.PumpNo == nozzleList!![i].Pump!!.PumpNo && fuelSaleTransaction.NozzleNo == nozzleList!![i].NozzleNo)
                return nozzleIdList!![i]
        }
        return null
    }

    private fun findNozzleByFuelSaleTransaction(fuelSaleTransaction: FuelSaleTransaction): Nozzle? {
        for (n in nozzleList!!) {
            if (fuelSaleTransaction.PumpNo == n.Pump!!.PumpNo && fuelSaleTransaction.NozzleNo == n.NozzleNo)
                return n
        }
        return null
    }

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

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

    override fun getCount(): Int {
        return transactionStatus!!.count()
    }
}