package com.duolebo.blyrobot.data

import android.content.Context
import android.util.Log
import com.duolebo.blyrobot.util.AdbUtil
import com.duolebo.blyrobot.util.Constants
import org.json.JSONObject
import net.gotev.uploadservice.UploadNotificationConfig
import net.gotev.uploadservice.ftp.FTPUploadRequest
import org.json.JSONArray
import java.io.File
import java.text.SimpleDateFormat
import java.util.*


class Task {
    private lateinit var packageName: String
    private lateinit var launcher: String
    private lateinit var imagePath: String
    private var launchDelay = 15
    private var context: Context
    private val imageDateFormat = SimpleDateFormat("yyyy_MM_dd_HH_mm_ss", Locale.CHINA)
    var proc: Process ?= null

    public constructor(context: Context) {
        this.context = context
    }

    fun from(json: JSONObject) {
        this.packageName = json.optString(Constants.PACKAGE_NAME)
        this.launcher = json.optString(Constants.LAUNCHER)
        this.launchDelay = json.optInt(Constants.LAUNCH_DELAY, 15)
        this.imagePath = this.context.cacheDir.absolutePath + "/" + this.packageName
        val dir = File(this.imagePath)
        if (!dir.exists())
            dir.mkdirs()
    }

    fun start() {
        this.launchApp()
    }

    fun finish() {
        AdbUtil.stopApp(this.packageName)
    }

    fun launchApp(reset: Boolean = true) {
        if (reset) {
            AdbUtil.resetApp(this.packageName)
        }

        AdbUtil.launchApp("{$packageName}/{$launcher}")
        Thread.sleep(launchDelay * 1000L)
    }

    private fun capture() {
        proc?.destroy()
        Thread(Runnable {
            AdbUtil.killTcpdump()
        }).start()
        Thread.sleep(3000)
        Thread(Runnable {
            proc = AdbUtil.tcpCapture("")
        }).start()
    }

    private fun parseCaptureFile(filterUrl: String) {
        val file = File("/sdcard/capture.txt")
        val lines = file.readLines()
        val playUrlItems = JSONArray()

        var partUrl = ""
        var timeStr = ""
        val tagGet = "GET /"
        lines.forEach {
            if (it.contains("IP (")) {
                val end = it.indexOf('.')
                timeStr = it.substring(0, end)
            }

            if (it.contains(tagGet)) {
                val start = it.indexOf(tagGet) + tagGet.length - 1
                val end = it.lastIndexOf(' ')
                partUrl = it.substring(start, end)
            }

            if (it.contains("Host")) {
                val start = it.indexOf(' ') + 1
                val host = it.substring(start)
                val url = "http://$host$partUrl"
                val item = JSONObject()
                item.put("url", url)
                item.put("time", timeStr)
                playUrlItems.put(item)
                partUrl = ""
            }
        }

        if (playUrlItems.length() > 0) {
            for (i in 0..playUrlItems.length()) {
                playUrlItems.get(i)
            }
        }
    }

    fun screenShot() {
        val time = imageDateFormat.format(Date())
        val imagePath = this.imagePath + "/{$packageName}_$time.png"
        AdbUtil.screenShot(imagePath)
    }

    fun uploadImage() {
        try {
            val uploadRequest = FTPUploadRequest(context, "ftp.duolebo.com", 21)
                    .setUsernameAndPassword("user", "password")
                    .setNotificationConfig(UploadNotificationConfig())
                    .setMaxRetries(4)

            var dir = File(imagePath)
            dir.listFiles().forEach {
                uploadRequest.addFileToUpload(it.absolutePath, "/remote/path")
            }

            val uploadId = uploadRequest.startUpload()
        } catch (exc: Exception) {
            Log.e("AndroidUploadService", exc.message, exc)
        }

    }
}