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 com.duolebo.blyrobot.service.BylRobotService
import com.duolebo.blyrobot.util.AdbUtil
import com.duolebo.blyrobot.util.Constants
import com.duolebo.blyrobot.util.ShellUtils
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {

    private val TAG = "MainActivity"

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

//        val result = ShellUtils.execCommand("killall", true)
//        Log.i(TAG, result.errorMsg + " " + result.errorMsg)
        val hasRoot = AdbUtil.checkRootPermission()
        if (hasRoot) {
            Log.i(TAG, "rooted...")
            textView.setText(R.string.tips_device_rooted)
        }
        else {
            textView.setText(R.string.tips_device_not_root)
        }

        startRobotService()

        startBtn.setOnClickListener{
            startRobot()
        }

        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)
    }

}
