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.appbase.AppBaseHandler
import com.duolebo.appbase.IAppBaseCallback
import com.duolebo.appbase.IProtocol
import com.duolebo.blyrobot.data.ApkInfo
import com.duolebo.blyrobot.data.AppInfoData
import com.duolebo.blyrobot.data.Task
import com.duolebo.blyrobot.protocol.GetAppInfoProtocol
import com.duolebo.blyrobot.tools.FtpManager
import com.duolebo.blyrobot.tools.TaskManager
import com.duolebo.blyrobot.util.AdbUtil
import com.duolebo.blyrobot.util.AppUtil
import com.duolebo.blyrobot.util.Config
import com.duolebo.blyrobot.util.Constants
import org.json.JSONObject
import java.util.*

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

    private val TAG = "BylRobotService"
    private var count = 0

    private lateinit var dataHandler: AppBaseHandler
    private lateinit var apkInfoProtocol: GetAppInfoProtocol

    private val broadcastReceiver = object : BroadcastReceiver() {
        override fun onReceive(p0: Context?, intent: Intent?) {
            if (intent != null) {
                val cmd = intent.getStringExtra(Constants.KEY_CMD)
                when (cmd) {
                    Constants.CMD_START -> loadTask()
                    Constants.CMD_STOP -> stopTask()
                }
            }
        }
    }

    override fun onCreate() {
        super.onCreate()
        FtpManager.instance.init(this)
        initBroadcast()
//        requestAppList()
    }

    private fun initBroadcast() {
        Log.i(TAG, "initBroadcast...")
        val intentFilter = IntentFilter(Constants.ACTION_LOCAL_SERVICE)
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, intentFilter)
    }

    private fun requestAppList() {
        apkInfoProtocol = GetAppInfoProtocol(this, Config.instance)
        this.dataHandler = AppBaseHandler(this)
        apkInfoProtocol.execute(this.dataHandler)
    }


    private fun loadTask() {
        Log.i(TAG, "loadTask...")

        if (Config.instance.isDebug) {
            val task = Task(this)
            val apkInfo = ApkInfo()
            val apkJson = JSONObject(AppUtil.readFromAssert(this, "test.json"))
            apkInfo.from(apkJson)
            task.from(apkInfo)
            TaskManager.instance.add(task)
        }

        TaskManager.instance.start()
    }

    private fun stopTask() {
        TaskManager.instance.stop()
    }


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

    override fun onProtocolFailed(protocol: IProtocol?) {
    }

    override fun onHttpFailed(protocol: IProtocol?) {
    }

    override fun onProtocolSucceed(protocol: IProtocol?) {
        if (protocol is GetAppInfoProtocol) {
            val appInfoData =  protocol.data as AppInfoData

            for (apkInfo in appInfoData.apkInfos) {
                if (apkInfo.monitoring && AppUtil.isAppInstalled(this, apkInfo.packageName)) {
                    val task = Task(this.applicationContext)
                    task.from(apkInfo)
                    TaskManager.instance.add(task)
                }
            }
        }
    }
}