package com.example.music

import android.content.Context
import android.media.MediaPlayer
import android.media.PlaybackParams
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import java.io.FileOutputStream
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit


class MainActivity : ComponentActivity() {
    companion object {
        var mContext:Context? = null
    }
    var webthread = false
    override fun onCreate (savedInstanceState:Bundle?) {

        super.onCreate (savedInstanceState)
        setContentView (R.layout.activity_main)
        mContext = this
        val executor = Executors.newSingleThreadExecutor()//create a new thread

        executor.execute {  //This starts the thread.  It starts a thread running the code in the braces
            doInBackground ("http://philos.nmu.edu/polka/polka.mp3")
        }

         while (!webthread) ;
    }

    override fun onResume () {
        super.onResume()
        try {
            val mp = MediaPlayer()
            val path: String = mContext!!.applicationInfo.dataDir + "/polka.mp3"

            /*
            mp.setDataSource ("http://philos.nmu.edu/polka/polka.mp3")
            */
            Log.e ("MUSIC",path)
            mp.setDataSource (path)

            mp.prepare()
            /*
            val params: PlaybackParams = mp.getPlaybackParams()
            params.setSpeed(0.5f)
            mp.setPlaybackParams(params)
            */

            mp.start()  //It plays in the background, the app is still running.
            try {
                TimeUnit.SECONDS.sleep (10)  //I sleep for ten seconds and then throw an exception
            } catch (e:Exception) {
            }
            mp.pause ()
            try {
                TimeUnit.SECONDS.sleep (5)
            } catch (e:Exception) {
            }
            mp.start ()
            try {
                TimeUnit.SECONDS.sleep (5)
            } catch (e:Exception) {
            }
            mp.reset()
            mp.setDataSource (path)
            mp.prepare()
            mp.start()


        } catch (e:Exception) {
            e.printStackTrace()
        }

    }

    fun doInBackground(url: String)  {

        try {
            val infile = java.net.URL(url).openStream()  //open up the web address
            val path: String = mContext!!.applicationInfo.dataDir + "/polka.mp3"
            val dbfile: FileOutputStream? = FileOutputStream(path)
            while (true) {  //copying the assets folder into the data directory
                val ch: Int = infile!!.read()
                if (ch == -1) break
                dbfile!!.write(ch)
            }
            dbfile!!.flush()
            dbfile.close()
        } catch (e:Exception) {
//            Log.e("Error",e.message!!)
            e.printStackTrace()
        }
        webthread = true
    }

}

