package com.example.milestone.milestonemobilesdkplaybacksample

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import com.milestonesys.xpmobilesdk.communication.CommunicationCommand
import java.util.*

import com.milestonesys.xpmobilesdk.callbacks.VideoReceiver
import com.milestonesys.xpmobilesdk.communication.VideoCommand
import android.graphics.BitmapFactory
import java.io.ByteArrayInputStream
import java.io.IOException
import android.graphics.Bitmap
import android.view.View
import android.widget.ImageButton
import android.widget.ImageView
import com.milestonesys.xpmobilesdk.communication.LiveVideo
import com.milestonesys.xpmobilesdk.communication.PlaybackVideo

/**
 * Activity that is playing playback video using XPMobileSDK
 */
class PlaybackActivity : AppCompatActivity(), VideoReceiver {

    private var applicationObject:SDKSampleApplication? = null
    private var cameraName:String? = null
    private var cameraId:UUID? = null
    private var bais: ByteArrayInputStream? = null
    private var bmp: Bitmap? = null
    private var videoView: ImageView? = null
    private var playbackVideo:PlaybackVideo? = null

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

        //Image view to show video on
        videoView = findViewById<ImageView>(R.id.videoView)
        applicationObject = application as SDKSampleApplication?

        //Parsing data from the intent to request video
        var currentIntent = intent
        cameraName = currentIntent.getStringExtra("cameraName")
        cameraId = UUID.fromString(currentIntent.getStringExtra("cameraId"))

        //Setting up video settings
        val videoProps = HashMap<String, String>()
        videoProps.put(CommunicationCommand.PARAM_WIDTH, videoView?.width.toString())
        videoProps.put(CommunicationCommand.PARAM_HEIGHT, videoView?.height.toString())
        videoProps.put(CommunicationCommand.PARAM_USER_DOWNSAMPLING, "No")
        videoProps.put(CommunicationCommand.PARAM_RESIZE_AVAILABLE, "Yes")

        //Setting up video channel properties
        val allProperties = HashMap<String, Any>()
        allProperties.put(LiveVideo.CAMERA_ID_PROPERTY, cameraId.toString())
        allProperties.put(LiveVideo.VIDEO_PROPERTIES, videoProps)
        allProperties.put(LiveVideo.FPS_PROPERTY, "8")

        Thread(Runnable {
            //Instancing playback object
            playbackVideo = applicationObject?.xpMobileSDK?.requestPlaybackVideo(this,allProperties)
        }).start()


        //Adding play forward button click listener
        val btnForward = findViewById <ImageButton>(R.id.playForwards) as ImageButton
        btnForward.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View) {
                //Makes play backward call in separate thread via the playback object
                Thread(Runnable { playbackVideo?.PlayForward() }).start()
            }
        })
        //Adding play backward button click listener
        val btnBackward = findViewById <ImageButton>(R.id.playBackwards) as ImageButton
        btnBackward.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View) {
                //Makes play forward call in separate thread via the playback object
                Thread(Runnable { playbackVideo?.PlayBackward() }).start()
            }
        })
        //Adding play pause button click listener
        val playOrPause = findViewById <ImageButton>(R.id.playOrPause) as ImageButton
        playOrPause.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View) {
                //Makes pause call in separate thread via the playback object
                Thread(Runnable { playbackVideo?.Pause() }).start()
            }
        })
    }


    //Stopping video on pause
    override fun onPause() {
        super.onPause()
        Thread(Runnable { playbackVideo?.Pause() }).start()
    }
    /**
     * Converts response from ByteArrayInputStream to bitmap and presents it in imageview
     */
    override fun receiveVideo(videoCommand: VideoCommand) {
        if (videoCommand.payloadSize > 0) {
            try {
                bais?.close()
            } catch (e3: IOException) {
            }

            bais = ByteArrayInputStream(videoCommand.payload, 0, videoCommand.payloadSize)
            bmp = BitmapFactory.decodeStream(bais)
            try {
                runOnUiThread {
                    if (bmp != null) {
                        videoView?.setImageBitmap(bmp)
                    }
                }

            } catch (e: OutOfMemoryError) {
                synchronized(this) {
                    try {
                        Thread.sleep(1500)
                    } catch (e1: InterruptedException) {
                    }

                }
            } finally {
                try {
                    bais?.close()
                } catch (e: Exception) {
                }

                bais = null

            }
        }
    }

}
