package com.tencent.liteav.demo.player.viewmodel

import android.content.Context
import androidx.work.CoroutineWorker
import androidx.work.WorkerParameters
import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONArray
import com.alibaba.fastjson2.JSONObject
import com.tencent.liteav.demo.player.http.CourseApi
import com.tencent.liteav.demo.player.http.HttpManager
import com.tencent.liteav.demo.player.util.ModelCourse
import com.tencent.liteav.demo.superplayer.database.PlayerDatabaseProvider
import com.tencent.liteav.demo.superplayer.database.entity.History
import com.tencent.liteav.demo.superplayer.database.entity.Record
import java.util.*

class UploadWorker(
    appContext: Context,
    params: WorkerParameters,
) : CoroutineWorker(appContext, params) {
    private val repository get() = (applicationContext as PlayerDatabaseProvider).getPlayerRepository()

    override suspend fun doWork(): Result {
        val courseId = inputData.getString("courseId")!!
        val sectionList = repository.queryAllHistory(courseId)

        val records = mutableListOf<ModelCourse.Records>()
        for (section in sectionList) {
            val history = repository.queryAllSectionHistory(courseId, section)
            val lastRecord = repository.queryRecord(courseId, section)
            val result = processPerSection(history, lastRecord)

            val record = ModelCourse.Records().apply {
                aiCourseItemId = section
                intervals = result.toString()
                validDuration = result.fold(0L) { t, p ->
                    t + p[1] - p[0] + 1
                }
                lastTime = history.lastOrNull()?.end ?: lastRecord?.lastTime ?: 0
            }

            records.add(record)
        }

        batchUpload(courseId, records)
        return Result.success()
    }

    /* 针对每一节处理 */
    private fun processPerSection(
        historyList: List<History>,
        lastRecord: Record?,
    ): List<List<Long>> {
        if (historyList.isEmpty()) return listOf()

        // 先把本地的记录处理一遍
        Collections.sort(historyList)
        var combineHistory = mutableListOf<Interval>()

        var left = historyList[0].start
        var right = historyList[0].end

        for (i in historyList.indices) {
            if (historyList[i].start <= right) {
                right = Math.max(historyList[i].end, right)
            } else {
                val p = Interval(left, right)
                combineHistory.add(p)

                left = historyList[i].start
                right = historyList[i].end
            }
        }

        val p = Interval(left, right)
        combineHistory.add(p)
        // 处理本地记录完成

        // 检查有没有上次记录并准备合并处理
        lastRecord?.apply {
            val lastResult = JSON.parseArray(this.intervals, List::class.java)
            for (item in lastResult) {
                val s = item[0] as Int
                val e = item[1] as Int
                combineHistory.add(Interval(s.toLong(), e.toLong()))
            }

            combineHistory.sort()

            val sortRecord = mutableListOf<Interval>()
            var lt = combineHistory[0].start
            var rt = combineHistory[0].end

            for (i in combineHistory.indices) {
                if (combineHistory[i].start <= rt) {
                    rt = Math.max(combineHistory[i].end, rt)
                } else {
                    sortRecord.add(Interval(lt, rt))
                    lt = combineHistory[i].start
                    rt = combineHistory[i].end
                }
            }

            sortRecord.add(Interval(lt, rt))
            combineHistory = sortRecord
        }

        val list = mutableListOf<List<Long>>()

        for (interval in combineHistory) {
            list.add(listOf(interval.start, interval.end))
        }

        return list
    }

    /* 分批次上传历史记录 */
    private suspend fun batchUpload(courseId: String, records: List<ModelCourse.Records>) {
        val api: CourseApi = HttpManager.create()
        val result = api.uploadHistory(records)
        if (result.status == 200) {
            repository.deleteAllHistory(courseId = courseId)
        }
    }

    private data class Interval(
        public val start: Long,
        public val end: Long,
    ) : Comparator<Interval>, Comparable<Interval> {
        override fun compare(o1: Interval, o2: Interval): Int {
            if (o1.start < o2.start) return -1
            if (o1.start > o2.start) return 1

            if (o1.end < o2.end) return 1;
            if (o1.end > o2.end) return -1

            return 0;
        }

        override fun compareTo(other: Interval): Int {
            if (this.start < other.start) return -1
            if (this.start > other.start) return 1

            if (this.end < other.end) return 1;
            if (this.end > other.end) return -1

            return 0;
        }

    }
}
