package etelligens.com.foodsafety.PrintLabel.PrintClasses

import android.annotation.SuppressLint
import android.app.Activity
import android.bluetooth.BluetoothDevice
import android.content.Context
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.Toolbar
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import etelligens.com.foodsafety.R

class ScanningActivity : AppCompatActivity() {
    private lateinit var bluetooth: Bluetooth
    private var devices = ArrayList<BluetoothDevice>()
    private lateinit var bluetoothAdapter: BluetoothDevicesAdapter
    var toolbar: Toolbar? = null
    var printers: ListView? = null
   // var refreshLayout: SwipeRefreshLayout? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_scanning)
        toolbar=findViewById(R.id.my_toolbar)as Toolbar?
        printers=findViewById(R.id.printers)
        bluetoothAdapter = BluetoothDevicesAdapter(this)
        bluetooth = Bluetooth(this)
        setup()
    }

    private fun setup() {
        initViews()
        initListeners()
        initDeviceCallback()
    }

    private fun initDeviceCallback() {
        bluetooth.setDiscoveryCallback(object : DiscoveryCallback {
            override fun onDiscoveryStarted() {
               // refreshLayout?.isRefreshing = true
                toolbar?.title = "Scanning.."
                devices.clear()
                devices.addAll(bluetooth.pairedDevices)
                Log.e("devices===", devices.toString())
                bluetoothAdapter.notifyDataSetChanged()
            }

            override fun onDiscoveryFinished() {
                toolbar?.title = if (devices.isNotEmpty()) "Select a Printer" else "No devices"
               // refreshLayout?.isRefreshing = false
            }

            override fun onDeviceFound(device: BluetoothDevice) {
                if (!devices.contains(device)) {
                    devices.add(device)
                    bluetoothAdapter.notifyDataSetChanged()
                }
            }

            override fun onDevicePaired(device: BluetoothDevice) {
                FinalPrint.setPrinter(device.name, device.address)
                Toast.makeText(this@ScanningActivity, "Device Paired", Toast.LENGTH_SHORT).show()
                bluetoothAdapter.notifyDataSetChanged()
                setResult(Activity.RESULT_OK)
                this@ScanningActivity.finish()
            }

            override fun onDeviceUnpaired(device: BluetoothDevice) {
                Toast.makeText(this@ScanningActivity, "Device unpaired", Toast.LENGTH_SHORT).show()
                val pairedPrinter = FinalPrint.getPairedPrinter()
                if (pairedPrinter != null && pairedPrinter.address == device.address)
                    FinalPrint.removeCurrentPrinter()
                devices.remove(device)
                bluetoothAdapter.notifyDataSetChanged()
                bluetooth.startScanning()
            }

            override fun onError(message: String) {
                Toast.makeText(this@ScanningActivity, "Error while pairing", Toast.LENGTH_SHORT).show()
                bluetoothAdapter.notifyDataSetChanged()
            }
        })
    }

    private fun initListeners() {
       // refreshLayout?.setOnRefreshListener { bluetooth.startScanning() }
        printers?.setOnItemClickListener { _, _, i, _ ->
            val device = devices[i]
            if (device.bondState == BluetoothDevice.BOND_BONDED) {
                FinalPrint.setPrinter(device.name, device.address)
                setResult(Activity.RESULT_OK)
                this@ScanningActivity.finish()
            } else if (device.bondState == BluetoothDevice.BOND_NONE)
                bluetooth.pair(devices[i])
            bluetoothAdapter.notifyDataSetChanged()
        }
    }

    private fun initViews() {
        printers?.adapter=bluetoothAdapter

    }

    override fun onStart() {
        super.onStart()

            bluetooth.onStart()
            if (!bluetooth.isEnabled)
                bluetooth.enable()
            Handler().postDelayed({
                bluetooth.startScanning()
            }, 1000)


    }

    override fun onStop() {
        super.onStop()
        bluetooth.onStop()
    }

    companion object {
        const val SCANNING_FOR_PRINTER = 115
    }

   /* inner class BluetoothDevicesAdapter(private val devices: List<BluetoothDevice>) : RecyclerView.Adapter<BluetoothDevicesAdapter.ViewHolder>() {

        // create new views
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
            // inflates the card_view_design view
            // that is used to hold list item
            val view = LayoutInflater.from(parent.context)
                .inflate(R.layout.bluetooth_device_row, parent, false)

            return ViewHolder(view)
        }

        // binds the list items to a view
        override fun onBindViewHolder(holder: ViewHolder, position: Int) {

            val BluetoothDevice = devices[position]

            if (devices[position].name.isNullOrEmpty()){
                holder.name.setText(devices[position].address)
            }else{
                holder.name.setText(devices[position].name)
            }
            when (devices[position].bondState) {
                BluetoothDevice.BOND_BONDED -> "Paired"
                BluetoothDevice.BOND_BONDING -> "Pairing.."
            // sets the image to the imageview from our itemHolder class
           // holder.imageView.setImageResource(ItemsViewModel.image)

            // sets the text to the textview from our itemHolder class
          //  holder.textView.text = ItemsViewModel.text

        }

        // return the number of the items in the list
        override fun getItemCount(): Int {
            return devices.size
        }

        // Holds the views for adding it to image and text
        inner class ViewHolder(ItemView: View) : RecyclerView.ViewHolder(ItemView) {
            val name: TextView = itemView.findViewById(R.id.name)
            val deviceStatus: TextView = itemView.findViewById(R.id.pairStatus)
        }
    }
*/
   /* inner class BluetoothDevicesAdapter(private val context: Context, private val device: ArrayList<BluetoothDevice>) : BaseAdapter()  {
        override fun getCount(): Int {
            Log.e("size==", device.size.toString())
            return device.size
        }

       override fun getItem(position: Int): Any {
           return position
       }

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

       override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            return LayoutInflater.from(context)
                .inflate(R.layout.bluetooth_device_row, parent, false).apply {
                    findViewById<TextView>(R.id.name).text = if (device[position].name.isNullOrEmpty()) device[position].address else device[position].name
                    findViewById<TextView>(R.id.pairStatus).visibility = if (device[position].bondState != BluetoothDevice.BOND_NONE) View.VISIBLE else View.INVISIBLE
                    findViewById<TextView>(R.id.pairStatus).text = when (device[position].bondState) {
                        BluetoothDevice.BOND_BONDED -> "Paired"
                        BluetoothDevice.BOND_BONDING -> "Pairing.."
                        else -> ""
                    }
                }
        }
    }*/

    inner class BluetoothDevicesAdapter(context: Context) : ArrayAdapter<BluetoothDevice>(context, android.R.layout.simple_list_item_1) {
        override fun getCount(): Int {
            return devices.size
        }

        @SuppressLint("ViewHolder", "CutPasteId")
        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            return LayoutInflater.from(context)
                .inflate(R.layout.bluetooth_device_row, parent, false).apply {
                    findViewById<TextView>(R.id.name).text = if (devices[position].name.isNullOrEmpty()) devices[position].address else devices[position].name
                    findViewById<TextView>(R.id.pairStatus).visibility = if (devices[position].bondState != BluetoothDevice.BOND_NONE) View.VISIBLE else View.INVISIBLE
                    findViewById<TextView>(R.id.pairStatus).text = when (devices[position].bondState) {
                        BluetoothDevice.BOND_BONDED -> "Paired"
                        BluetoothDevice.BOND_BONDING -> "Pairing.."
                        else -> ""
                    }
                    findViewById<ImageView>(R.id.pairedPrinter).visibility = if (FinalPrint.getPairedPrinter()?.address == devices[position].address) View.VISIBLE else View.GONE
                }
        }
    }
}
