package com.duolebo.blyrobot

import android.content.Intent
import android.os.Bundle
import android.support.v4.content.LocalBroadcastManager
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Button
import com.duolebo.blyrobot.service.BylRobotService
import com.duolebo.blyrobot.util.Constants

class MainActivity : AppCompatActivity() {

    private val TAG = "MainActivity"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.i(TAG, "onCreate....")
        setContentView(R.layout.activity_main)

        startRobotService()

        val startBtn = findViewById<Button>(R.id.startBtn)
        startBtn.setOnClickListener{
            startRobot()
        }

        val stopBtn = findViewById<Button>(R.id.stopBtn)
        stopBtn.setOnClickListener{
            stopRobot()
        }
        startBtn.requestFocus()
    }

    private fun startRobotService() {
        startService(Intent(this, BylRobotService::class.java))
    }

    private fun startRobot() {
        Log.i(TAG, "startRobot...")
        val intent = Intent(Constants.ACTION_LOCAL_SERVICE)
        intent.putExtra(Constants.KEY_CMD, Constants.CMD_START)
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }

    private fun stopRobot() {
        val intent = Intent(Constants.ACTION_LOCAL_SERVICE)
        intent.putExtra(Constants.KEY_CMD,  Constants.CMD_STOP)
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent)
    }

}
