package com.duolebo.blyrobot.service

import android.annotation.SuppressLint
import android.app.Service
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.IBinder
import android.support.v4.content.LocalBroadcastManager
import android.util.Log
import com.duolebo.blyrobot.data.Task
import com.duolebo.blyrobot.util.AdbUtil
import com.duolebo.blyrobot.util.AppUtil
import com.duolebo.blyrobot.util.Constants
import org.json.JSONObject
import java.util.*

@SuppressLint("Registered")
class BylRobotService: Service() {

    private val TAG = "BylRobotService"
    private var timer: Timer? = null
    private var count = 0
    private val tasks = ArrayList<Task>()

    private val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, p1: Intent?) {

        }
    }

    override fun onCreate() {
        super.onCreate()

        timer = Timer()

        timer!!.schedule(object: TimerTask() {
            override fun run() {
//                testKey()
                testCapture()
//                screenShot()
                count++
                if (count > 2) {
                    cancelTimer()
//                    proc?.destroy()
                }
            }
        },2000, 10*1000)
    }

    private fun initBroadcast() {
        val intentFilter = IntentFilter(Constants.BC_SERVICE)
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter)
    }

    private fun loadTask() {
        val task = Task(this)
        task.from(JSONObject(AppUtil.readFromAssert(this, "test.json")))
        tasks.add(task)
    }


    private fun screenShot() {
        Thread(Runnable {

        }).start()
    }

    private fun testKey() {
        Thread(Runnable {
            AdbUtil.sendMultiKey("down/up/right",0.5f)
        }).start()
    }

    var proc: Process ?= null
    private fun testCapture() {
        proc?.destroy()
        Thread(Runnable {
            AdbUtil.killTcpdump()
        }).start()
        Thread.sleep(3000)
        Thread(Runnable {
            proc = AdbUtil.tcpCapture("")
        }).start()
    }

    private fun cancelTimer() {
        timer?.cancel()
        timer = null
    }

    override fun onBind(p0: Intent?): IBinder {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onDestroy() {
        Log.i(TAG, "destroy...")
        super.onDestroy()
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver)
        cancelTimer()
    }
}