package com.example.milestone.milestonemobilesdkplaybacksample

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.TextView
import com.milestonesys.xpmobilesdk.communication.CommunicationItem

/**
 *  Activity showing all the available cameras in a list
 */
class CameraListActivity : AppCompatActivity() {

    private var applicationObject: SDKSampleApplication? = null
    private var cameraListView: ListView? = null
    private var camerasAdapter: CameraAdapter? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_camera_list)

        applicationObject = application as SDKSampleApplication?
        cameraListView = findViewById<ListView>(R.id.cameraList)
        camerasAdapter = CameraAdapter(this, applicationObject!!.allAvailableCameras!!)
        cameraListView?.setAdapter(camerasAdapter)


        cameraListView?.setOnItemClickListener { adapterView: AdapterView<*>, view1: View, i: Int, l: Long ->
            var cameraPressed: CommunicationItem = adapterView.getItemAtPosition(i) as CommunicationItem

            val b = Bundle()
            b.putString("cameraName", cameraPressed.name)
            b.putString("cameraId", cameraPressed.id.toString())
            val intent = Intent(
                    this,
                    PlaybackActivity::class.java
            )
            intent.putExtras(b);
            startActivity(intent)

        }
    }
}

class CameraAdapter(context: Context, cameras: ArrayList<CommunicationItem>?) : ArrayAdapter<CommunicationItem>(context, 0, cameras) {

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
        var convertView = convertView
        if (convertView == null) {
            convertView = LayoutInflater.from(getContext()).inflate(R.layout.camera_list_item, parent, false);
        }

        val cameraName: TextView = convertView?.findViewById<TextView>(R.id.cameraName) as TextView
        cameraName.setText(getItem(position).name)
        return convertView!!
    }
}
