package com.wayne.www.waynelib.ui.view

import android.content.Context
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Handler
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.View.OnClickListener
import android.view.View.OnLongClickListener
import android.view.ViewGroup
import android.widget.*
import com.bumptech.glide.Glide
//import com.bumptech.glide.request.target.GlideDrawableImageViewTarget
import com.wayne.www.waynelib.common.Tuple
import com.wayne.www.waynelib.fdc.model.FuelSaleTransaction
import com.wayne.www.waynelib.fdc.model.Nozzle
import com.wayne.www.waynelib.fdc.model.Pump
import com.wayne.www.waynelib.fdc.model.PumpOrNozzleState
import com.wayne.www.waynelib.listener.OnDropDownMenuClickListener
import com.wayne.www.waynelib.listener.OnPropertyChangedListener
import com.wayne.www.waynelib.ui.R
import com.wayne.www.waynelib.ui.adapter.LatestTrxsAdapter
import com.wayne.www.waynelib.ui.widget.NestedListview
import com.wayne.www.waynelib.util.Util
import org.slf4j.LoggerFactory.getLogger
import java.util.*


/**
 * Created by Justin on 5/8/2018.
 */
class NozzleGridView : FrameLayout, OnPropertyChangedListener {

    internal var LOG_TAG = "MobileCashPos.NozzleGridView"
    private val fileLogger = getLogger(NozzleGridView::class.java)
    private var fuelingView: View? = null
    private var nonFuelingView: View? = null
    private var dropDownControlMenuItems: List<Tuple<String, Int>> = ArrayList()
    private val needRecaculatePumpImageViewHeight = true
    private val onDropDownMenuClickListener = ArrayList<OnDropDownMenuClickListener>()
    private var titleTextView: TextView? = null
    private var titleTextViewFueling: TextView? = null

    private var pumpImageView: ImageView? = null
    // by attaching this layout to main view to implement the turn on and off effect.
    private var dropDownControlMenuLayout: LinearLayout? = null
    private var pump: Pump? = null
    private var loyaltyPointsInput: Button? = null
    private var shortCodeInput: Button? = null
    private var fuelDescription: TextView? = null
    private var fuelDescriptionFueling: TextView? = null
    private var fuelPrice: TextView? = null
    private var currentAmount: TextView? = null
    private var currentVolumn: TextView? = null
    private var latestTrxFuelPrice: TextView? = null
    private var latestTrxAmount: TextView? = null
    private var latestTrxVolume: TextView? = null
    private var numOfNozzles = 0
    private var nozzleName = ""
    private var mapImages: HashMap<Int, Bitmap> = hashMapOf()
    private var listViewTrxs: NestedListview? = null
    private var adapterTrxs: LatestTrxsAdapter? = null
    private var parentGridView: GridView? = null
    private var lastState: PumpOrNozzleState? = PumpOrNozzleState.Idle

    constructor(context : Context, items : List<Tuple<String, Int>>, numOfNozzles: Int, nozzleName: String, gridView: GridView) : super(context) {
        this.numOfNozzles = numOfNozzles
        this.dropDownControlMenuItems = items
        this.nozzleName = nozzleName
        this.parentGridView = gridView
        sharedConstructing(context)
    }

    companion object {
        var DISPLAY_FUELING_PROGRESS = true
    }

    private fun sharedConstructing(context: Context?) {
        val inflater = context?.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
        //initImage()
        if (numOfNozzles <= 2) {
            fuelingView = inflater.inflate(R.layout.pump_view_2_columns_fueling, null, false)
            nonFuelingView = inflater.inflate(R.layout.pump_view_2_columns, null, false)
        } else if (numOfNozzles == 3) {
            fuelingView = inflater.inflate(R.layout.pump_view_3_columns_fueling, null, false)
            nonFuelingView = inflater.inflate(R.layout.pump_view_3_columns, null, false)
        } else if (numOfNozzles == 4) {
            fuelingView = inflater.inflate(R.layout.pump_view_4_columns_fueling, null, false)
            nonFuelingView = inflater.inflate(R.layout.pump_view_4_columns, null, false)
        }

        if (!DISPLAY_FUELING_PROGRESS) {
            this.addView(nonFuelingView, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
        } else {
            this.addView(nonFuelingView, 0, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
            this.addView(fuelingView, 1, FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT))
        }

        setFuelingMode(false)

        //this.setOrientation(VERTICAL);
        //this.setBackgroundColor(0xFF9CE1B0);

        this.titleTextView = findViewById<View>(R.id.pump_view_title_TextView) as TextView
        this.titleTextViewFueling = findViewById<View>(R.id.pump_view_title_fueling) as TextView

        this.pumpImageView = findViewById<View>(R.id.pump_view_pump_ImageView) as ImageView
        this.pumpImageView?.setOnClickListener(OnClickListener {
            //            fileLogger.debug("Click on PumpView: " + this@NozzleGridView.getBindNozzle()?.NozzleNo)
//            for (l in this@NozzleGridView.onDropDownMenuClickListener) {
//                l.onItemViewClicked(this@NozzleGridView, null, ClickType.SingleClick)
//            }
//            //
//            if (getControlMenuOpeningState())
//                toggleDropdownMenu(false)
//            else
//                toggleDropdownMenu(true)
        })
        this.pumpImageView?.setOnLongClickListener(OnLongClickListener {
            fileLogger.debug("LongClick on PumpView: " + this@NozzleGridView.getBindNozzle()?.NozzleNo)
            val h = Handler()
            h.post {
                //((Vibrator) PumpView.this.context.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(150);
                for (l in this@NozzleGridView.onDropDownMenuClickListener) {
                    l.onMenuItemClicked(this@NozzleGridView, null, ClickType.RefreshTrxs)
                }

                if (getControlMenuOpeningState())
                    toggleDropdownMenu(false)
                else
                    toggleDropdownMenu(true)
            }
            true
        })
        this.dropDownControlMenuLayout = LinearLayout(context)
        this.dropDownControlMenuLayout?.setId(View.generateViewId())

        this.fuelDescription = findViewById<View>(R.id.fuel_grade_description) as TextView
        this.fuelDescriptionFueling = findViewById<View>(R.id.fuel_grade_description_fueling) as TextView
        this.fuelPrice = findViewById<View>(R.id.fuel_grade_price) as TextView
        this.currentAmount = findViewById<View>(R.id.pump_view_amount) as TextView
        this.currentVolumn = findViewById<View>(R.id.pump_view_volumn) as TextView
//        this.latestTrxFuelPrice = findViewById<View>(R.id.latest_trx_fuel_price) as TextView
//        this.latestTrxAmount = findViewById<View>(R.id.latest_trx_amount) as TextView
//        this.latestTrxVolume = findViewById<View>(R.id.latest_trx_volume) as TextView

        this.shortCodeInput = findViewById<View>(R.id.button_short_code_input) as Button

        this.shortCodeInput?.setOnClickListener(OnClickListener {
            fileLogger.debug("Click on PumpView: " + this@NozzleGridView.getBindNozzle()?.NozzleNo)
            if (listViewTrxs!!.count != 0) {
                val currentTrx = listViewTrxs?.getItemAtPosition(listViewTrxs?.lastVisiblePosition!!) as FuelSaleTransaction
                if (currentTrx != null) {
                    this.nozzle?.selectedTransaction = currentTrx
                    for (l in this@NozzleGridView.onDropDownMenuClickListener) {
                        l.onMenuItemClicked(this@NozzleGridView, null, ClickType.ShortCodeClick)
                    }
                    //
                    if (getControlMenuOpeningState())
                        toggleDropdownMenu(false)
                    else
                        toggleDropdownMenu(true)
                }
            }
        })

        this.loyaltyPointsInput = findViewById<View>(R.id.button_loyalty_point_input) as Button

        this.loyaltyPointsInput?.setOnClickListener(OnClickListener {
            fileLogger.debug("Click on PumpView: " + this@NozzleGridView.getBindNozzle()?.NozzleNo)
            if (listViewTrxs!!.count != 0) {
                val currentTrx = listViewTrxs?.getItemAtPosition(listViewTrxs?.lastVisiblePosition!!) as FuelSaleTransaction
                if (currentTrx != null) {
                    this.nozzle?.selectedTransaction = currentTrx
                    for (l in this@NozzleGridView.onDropDownMenuClickListener) {
                        l.onMenuItemClicked(this@NozzleGridView, null, ClickType.CashInputClick)
                    }
                    //
                    if (getControlMenuOpeningState())
                        toggleDropdownMenu(false)
                    else
                        toggleDropdownMenu(true)
                }
            }
        })

        listViewTrxs = findViewById(R.id.list_view_trxs) as NestedListview
        listViewTrxs?.scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY
//        listViewTrxs?.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(),
//                SystemClock.uptimeMillis(), MotionEvent.ACTION_CANCEL, 0f, 0f, 0))

        listViewTrxs?.setParent(parentGridView)
        listViewTrxs?.setOnItemLongClickListener { parent, view, position, id ->
            fileLogger.debug("LongClick on PumpView: " + this@NozzleGridView.getBindNozzle()?.NozzleNo)
            val h = Handler()
            h.post {
                //((Vibrator) PumpView.this.context.getSystemService(Context.VIBRATOR_SERVICE)).vibrate(150);
//                if (listViewTrxs!!.count != 0) {
//                    val currentTrx = listViewTrxs?.getItemAtPosition(listViewTrxs?.lastVisiblePosition!!) as FuelSaleTransaction
//                    this.nozzle?.selectedTransaction = currentTrx
//                }
//
//                if (nozzle!!.latestUnpaidTrx != null) {
                    for (l in this@NozzleGridView.onDropDownMenuClickListener) {
                        l.onMenuItemClicked(this@NozzleGridView, null, ClickType.RefreshTrxs)
                    }

                    if (getControlMenuOpeningState())
                        toggleDropdownMenu(false)
                    else
                        toggleDropdownMenu(true)
               // }
            }
            true
        }



//        listViewTrxs?.setOnItemClickListener { parent, view, position, id ->
//            fileLogger.debug("LongClick on PumpView: " + this@NozzleGridView.getBindNozzle()?.NozzleNo)
//            val h = Handler()
//            h.post {
//                currentSelection++;
//                if (currentSelection >= listViewTrxs!!.count) {
//                    currentSelection = 0
//                }
//                listViewTrxs?.setSelection(currentSelection)
//            }
//            true
//        }
    }

    private var currentSelection = 0

    fun refreshTrxList() {
        var trxs = this.nozzle!!.availableTransactions
        if (trxs != null && trxs?.count() != 0) {
            adapterTrxs!!.setData(trxs)
            adapterTrxs!!.notifyDataSetChanged()
            listViewTrxs?.setSelection(0)
            //currentSelection = 0
        }
    }

    fun getControlMenuOpeningState(): Boolean {
        val found = this.findViewById<View>(this.dropDownControlMenuLayout!!.getId())
        return found != null
    }

    fun getBindNozzle(): Nozzle? {
        return this.nozzle
    }

    enum class ClickType {
        SingleClick, LongClick, ShortCodeClick, CashInputClick, RefreshTrxs
    }

    override fun onPropertyChanged(sender: Any?, propertyName: String?) {
        fileLogger.debug("NozzleGridView (with nozzleId: " + this.nozzle?.NozzleNo + ") Property changed, sender: " + sender.toString() + ", propertyName: " + propertyName)
        this.updateUI(sender, propertyName)
    }

    private fun showLatestTrx(show: Boolean, latestTrx: FuelSaleTransaction? = null) {
        //fileLogger.info("Justin refresh transaction list, list length: ${this.nozzle!!.getTransactions()?.count()}")
        if (show) {
//            if (numOfNozzles == 2) {
//                setFuelingStatusImage(R.drawable.trx_details2)
//            } else if (numOfNozzles == 3) {
//                setFuelingStatusImage(R.drawable.trx_details3)
//            } else if (numOfNozzles == 4){
//                setFuelingStatusImage(R.drawable.trx_details4)
//            } else {
//                setFuelingStatusImage(R.drawable.trx_details4)
//            }
//            if (latestTrx != null) {
//                refreshTrxList()
//                latestTrxFuelPrice?.setText(latestTrx.UnitPrice.format(2))
//                latestTrxAmount?.setText(latestTrx.Amount.format(2))
//                latestTrxVolume?.setText(latestTrx.Volume.format(2))
           // }
//            latestTrxFuelPrice?.visibility = View.VISIBLE
//            latestTrxAmount?.visibility = View.VISIBLE
//            latestTrxVolume?.visibility = View.VISIBLE
            refreshTrxList()
            listViewTrxs?.visibility = View.VISIBLE
            pumpImageView?.visibility = View.INVISIBLE
        } else {
//            latestTrxFuelPrice?.visibility = View.INVISIBLE
//            latestTrxAmount?.visibility = View.INVISIBLE
//            latestTrxVolume?.visibility = View.INVISIBLE
            listViewTrxs?.visibility = View.INVISIBLE
            pumpImageView?.visibility = View.VISIBLE
        }
    }

    fun Double.format(digits: Int) = java.lang.String.format("%.${digits}f", this)

    private var nozzle: Nozzle? = null

    fun bindNozzle(nozzle: Nozzle) {
        this.nozzle = nozzle
        this.nozzle?.NozzleName = nozzleName

        adapterTrxs = LatestTrxsAdapter(context, this.nozzle!!.getTransactions(), numOfNozzles)
        listViewTrxs!!.setAdapter(adapterTrxs)
//        listViewTrxs!!.onItemLongClickListener = AdapterView.OnItemLongClickListener { parent, view, position, id ->
//
//            true
//        }
        listViewTrxs?.visibility = View.INVISIBLE
        this.updateUI()
        this.dropDownControlMenuLayout?.removeAllViews()
        for (i in this.dropDownControlMenuItems.indices) {
            val oneItem = this.dropDownControlMenuItems[i]
            val tv = TextView(this.context)
            tv.setId(View.generateViewId())
            tv.setTag(oneItem.second)
            tv.setText(oneItem.first)
            tv.setOnClickListener(OnClickListener { view ->
                val clicked = view as TextView
                fileLogger.debug("ControlMenu Item " + clicked.tag + " get clicked at PumpView: " + this@NozzleGridView.getBindNozzle()?.NozzleNo)
                val h = Handler()
                h.post {
                    for (l in this@NozzleGridView.onDropDownMenuClickListener) {

                        l.onMenuItemClicked(this@NozzleGridView, clicked.tag, ClickType.SingleClick)
                    }
                }
            })

            val lp = LinearLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT)
            lp.setMargins(0, 5, 0, 0)
            this.dropDownControlMenuLayout?.addView(tv, lp)
        }
        this.nozzle?.addOnPropertyChangedListener(this)
    }

    private fun updateUI(sender: Any? = null, propertyName: String? = "") {
        val latestTrx = nozzle?.latestUnpaidTrx
        this.titleTextView?.setText(nozzleName)
        this.titleTextViewFueling?.setText(nozzleName)
        if (nozzle?.GradeName != null && nozzle?.GradeName != "") {
            //this.fuelDescription?.setText("${nozzle?.GradeName} / ¥${nozzle?.FuelPrice}")
            this.fuelDescription?.setText("${nozzle?.GradeName}")
            this.fuelDescriptionFueling?.setText("${nozzle?.GradeName}")
        }
        setGifAnimationToImageViewByPumpState(nozzle?.currentState, latestTrx)

        if (sender != null) {
            if (sender is Nozzle) {
                if (propertyName == "GradeInfo" &&
                        sender.GradeName != null && !sender.GradeName.isEmpty()) {
                    //fuelDescription?.setText("${sender.GradeName} / ¥${sender.FuelPrice}")
                    fuelDescription?.setText("${sender.GradeName}")
                    fuelDescriptionFueling?.setText(sender.GradeName)
                }
                if (propertyName == "FuelingInProgress") {
                    if (sender.CurrentAmount != null && !sender.CurrentAmount.isEmpty()) {
                        val amount = sender.CurrentAmount.toFloat()
                        if (Util.getScreenWidth(context) > 720 && Util.getScreenHeight(context) >= 1920) {
                            if (amount >= 1000) {
                                when (numOfNozzles) {
                                    1,2 -> currentAmount!!.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 62f)
                                    3 -> currentAmount!!.setTextSize(TypedValue.COMPLEX_UNIT_DIP,52f)
                                    4 -> currentAmount!!.setTextSize(TypedValue.COMPLEX_UNIT_DIP,43f)
                                    else -> currentAmount!!.setTextSize(TypedValue.COMPLEX_UNIT_DIP,62f)
                                }
                            } else {
                                when (numOfNozzles) {
                                    1,2 -> currentAmount!!.setTextSize(TypedValue.COMPLEX_UNIT_DIP,65f)
                                    3 -> currentAmount!!.setTextSize(TypedValue.COMPLEX_UNIT_DIP,55f)
                                    4 -> currentAmount!!.setTextSize(TypedValue.COMPLEX_UNIT_DIP,50f)
                                    else -> currentAmount!!.setTextSize(TypedValue.COMPLEX_UNIT_DIP,65f)
                                }
                            }
                        }
                        currentAmount?.setText(sender.CurrentAmount)
                    }
                    if (sender.CurrentVolumn != null && !sender.CurrentVolumn.isEmpty()) {
                        currentVolumn?.setText(sender.CurrentVolumn)
                    }
                    if (sender.FuelPrice != null && !sender.FuelPrice.isEmpty()) {
                        fuelPrice?.setText(sender.FuelPrice)
                    }
                } else if (propertyName != "State") {
                    if (latestTrx != null) {
                        showLatestTrx(true, latestTrx)
                    } else {
                        showLatestTrx(false)
                        setFuelingStatusImage(R.drawable.pump_liq_estado_idle_hi_res)
                    }

                }
            }
        }
    }

    fun toggleDropdownMenu(turnOn: Boolean) {
        val found = this.findViewById<View>(this.dropDownControlMenuLayout!!.getId())
        if (turnOn && found == null && this.dropDownControlMenuItems.size > 0) {
            run {
                this.addView(this.dropDownControlMenuLayout, FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT))
                this.bringToFront()
            }
        } else if (turnOn == false && found != null)
            this.removeView(this.dropDownControlMenuLayout)
    }

    private fun setGifAnimationToImageViewByPumpState(state: PumpOrNozzleState?, latestTrx: FuelSaleTransaction? = null) {
        val apiLevelBelow19 = true
        lastState = state
        //GlideDrawableImageViewTarget imageViewTarget = new GlideDrawableImageViewTarget(this.pumpImageView);
        if (!apiLevelBelow19) {
//            val imageViewTarget = GlideDrawableImageViewTarget(this.pumpImageView, 1)
//            if (state == PumpOrNozzleState.Idle)
//                Glide.with(this.context).load(R.drawable.pump_liq_estado_idle).into(imageViewTarget)
//            else if (state == PumpOrNozzleState.Authorized)
//                Glide.with(this.context).load(R.drawable.pump_liq_estado_authorized).into(imageViewTarget)
//            else if (state == PumpOrNozzleState.Starting)
//                Glide.with(this.context).load(R.drawable.pump_liq_estado_starting).into(imageViewTarget)
//            else if (state == PumpOrNozzleState.Fueling)
//                Glide.with(this.context).load(R.drawable.pump_liq_estado_fuelling).into(imageViewTarget)
//            else if (state == PumpOrNozzleState.Calling)
//                Glide.with(this.context).load(R.drawable.pump_liq_estado_calling).into(imageViewTarget)
//            else if (state == PumpOrNozzleState.Closed)
//                Glide.with(this.context).load(R.drawable.pump_liq_estado_closed_group).into(imageViewTarget)
//            else if (state == PumpOrNozzleState.Error)
//                Glide.with(this.context).load(R.drawable.pump_liq_estado_error).into(imageViewTarget)
//            else if (state == PumpOrNozzleState.Unpaid)
//                Glide.with(this.context).load(R.drawable.pump_liq_estado_idle_unpaid_trx_rmb).into(imageViewTarget)
        } else {
            if (numOfNozzles <= 2) {
                if (state == PumpOrNozzleState.Fueling) {
                    setFuelingStatusImage(R.drawable.pump_liq_estado_fuelling_2)
                    setFuelingMode(true)
                } else {
                    setFuelingMode(false)
                    if (state == PumpOrNozzleState.Unpaid) {
                        showLatestTrx(true, latestTrx)
                    } else {
                        showLatestTrx(false)
                        if (state == PumpOrNozzleState.Idle)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_idle_2)
                        else if (state == PumpOrNozzleState.Authorized)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_authorized_2)
                        else if (state == PumpOrNozzleState.Starting)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_calling_2)
                        else if (state == PumpOrNozzleState.Calling)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_calling_2)
                        else if (state == PumpOrNozzleState.Closed)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_closed_group_2)
                        else if (state == PumpOrNozzleState.Error)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_error_2)
                    }
                }
            } else if (numOfNozzles == 3) {
                if (state == PumpOrNozzleState.Fueling) {
                    setFuelingMode(true)
                } else {
                    setFuelingMode(false)
                    if (state == PumpOrNozzleState.Unpaid) {
                        showLatestTrx(true, latestTrx)
                    } else {
                        showLatestTrx(false)
                        if (state == PumpOrNozzleState.Idle)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_idle_3)
                        else if (state == PumpOrNozzleState.Authorized)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_authorized_3)
                        else if (state == PumpOrNozzleState.Starting)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_calling_3)
                        else if (state == PumpOrNozzleState.Calling)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_calling_3)
                        else if (state == PumpOrNozzleState.Closed)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_closed_group_3)
                        else if (state == PumpOrNozzleState.Error)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_error_3)
                    }
                }
            } else if (numOfNozzles == 4) {
                if (state == PumpOrNozzleState.Fueling) {
                    setFuelingMode(true)
                } else {
                    setFuelingMode(false)
                    if (state == PumpOrNozzleState.Unpaid) {
                        showLatestTrx(true, latestTrx)
                    } else {
                        showLatestTrx(false)
                        if (state == PumpOrNozzleState.Idle)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_idle_4)
                        else if (state == PumpOrNozzleState.Authorized)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_authorized_4)
                        else if (state == PumpOrNozzleState.Starting)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_calling_4)
                        else if (state == PumpOrNozzleState.Calling)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_calling_4)
                        else if (state == PumpOrNozzleState.Closed)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_closed_group_4)
                        else if (state == PumpOrNozzleState.Error)
                            setFuelingStatusImage(R.drawable.pump_liq_estado_error_4)
                    }
                }
            }
        }
    }

    private fun initImage() {
        val imgIdList = listOf<Int>(R.drawable.pump_liq_estado_idle_3,
                R.drawable.pump_liq_estado_starting_3,
                R.drawable.pump_liq_estado_calling_3,
                R.drawable.pump_liq_estado_authorized_3,
                R.drawable.pump_liq_estado_closed_group_3,
                R.drawable.pump_liq_estado_error_3,
                R.drawable.trx_details2,
                R.drawable.trx_details3,
                R.drawable.trx_details4,
                R.drawable.pump_liq_estado_idle_hi_res,
                R.drawable.pump_liq_estado_idle_2,
                R.drawable.pump_liq_estado_starting_2,
                R.drawable.pump_liq_estado_calling_2,
                R.drawable.pump_liq_estado_authorized_2,
                R.drawable.pump_liq_estado_closed_group_2,
                R.drawable.pump_liq_estado_error_2,
                R.drawable.pump_liq_estado_idle_4,
                R.drawable.pump_liq_estado_starting_4,
                R.drawable.pump_liq_estado_calling_4,
                R.drawable.pump_liq_estado_authorized_4,
                R.drawable.pump_liq_estado_closed_group_4,
                R.drawable.pump_liq_estado_error_4
        )
        var map: HashMap<Int, Bitmap> = hashMapOf()

        for (id in imgIdList) {
            val opt = BitmapFactory.Options()
            opt.inPreferredConfig = Bitmap.Config.RGB_565
            opt.inPurgeable = true
            opt.inInputShareable = true
            val `is` = resources.openRawResource(id)
            val bm = BitmapFactory.decodeStream(`is`, null, opt)
            map[id] = bm!!
        }
        mapImages = map
    }

    private fun setFuelingStatusImage(id: Int) {
        pumpImageView?.setImageResource(id)
//        if (mapImages[id] != null && mapImages[id] is Bitmap) {
//            this.pumpImageView?.setImageBitmap(mapImages[id])
//        } else {
//            pumpImageView?.setImageResource(id)
//        }
//        var drawable =  this.pumpImageView?.drawable
//        val opt = BitmapFactory.Options()
//        opt.inPreferredConfig = Bitmap.Config.RGB_565
//        opt.inPurgeable = true
//        opt.inInputShareable = true
//        val `is` = resources.openRawResource(id)
//        val bm = BitmapFactory.decodeStream(`is`, null, opt)
//        this.pumpImageView?.setImageBitmap(bm)
//
//        if (drawable is BitmapDrawable) {
//            val bitmapDrawable = drawable as BitmapDrawable
//            val bitmap = bitmapDrawable.bitmap
//            bitmap.recycle()
//        }
    }

    private fun setFuelingMode(isFueling: Boolean) {
        if (isFueling) {
            this.getChildAt(0).visibility = View.INVISIBLE
            this.getChildAt(1).visibility = View.VISIBLE
            if (lastState != PumpOrNozzleState.Fueling) {
                currentAmount?.setText("0.00")
                currentVolumn?.setText("0.00")
            }
        } else {
            this.getChildAt(0).visibility = View.VISIBLE
            this.getChildAt(1).visibility = View.INVISIBLE
        }
    }

    fun addOnOnDropDownMenuClickListener(onDropDownMenuClickListener: OnDropDownMenuClickListener?) {
        this.onDropDownMenuClickListener.add(onDropDownMenuClickListener!!)
    }
}