package com.abbidot.tracker.vm

import android.content.Context
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.abbidot.baselibrary.util.LogUtil
import com.abbidot.tracker.bean.ReceiveDeviceData
import com.abbidot.tracker.retrofit2.NetworkApi
import com.abbidot.tracker.util.FileUtil
import com.abbidot.tracker.util.Util
import com.qmuiteam.qmui.util.QMUIDisplayHelper
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import kotlinx.coroutines.sync.withLock
import java.io.File
import java.io.FileOutputStream
import java.io.IOException


/**
 *Created  by .yzq on 2022/3/11/011.
 * @link
 * @description:设备日志上报
 */
class LogBleReportViewModel : ViewModel() {

    val mUploadLogLiveData = MutableLiveData<Result<String>>()
    val mUploadDeviceLogLiveData = MutableLiveData<Result<String>>()

    //线程同步锁 No upload
    private val mMutex = Mutex()


    /**
     * 处理日志上报的数据
     */
    fun dealLogReportData(context: Context, receiveData: ReceiveDeviceData) {
        viewModelScope.launch(Dispatchers.IO) {
            mMutex.withLock {
                val fileName = "${receiveData.mac}.txt"
                val file = File(
                    FileUtil.getDiskCacheDirectory(context, FileUtil.LOG_DIRECTORY_NAME), fileName
                )
                try {
                    // 追加创建文件输出流
                    val fos = FileOutputStream(file, true)
                    // 将数据写入文件
                    fos.write(receiveData.data)
                    // 关闭文件输出流
                    fos.close()
                } catch (e: IOException) {
                    e.printStackTrace()
                }
            }
        }
    }

    /**
     * 设备日志上传
     */
    fun uploadLog(context: Context, mac: String, deviceOutId: String) {
        //是否有网络功能
        if (QMUIDisplayHelper.hasInternet(context)) {
            viewModelScope.launch {
                mMutex.withLock {
                    try {
                        val fileName = "$mac.txt"
                        val file = File(
                            FileUtil.getDiskCacheDirectory(context, FileUtil.LOG_DIRECTORY_NAME),
                            fileName
                        )
                        if (file.exists()) {
                            val newFileName =
                                "${deviceOutId}_${mac}_${System.currentTimeMillis() / 1000}.txt"
                            val newFile = File(
                                FileUtil.getDiskCacheDirectory(
                                    context, FileUtil.LOG_DIRECTORY_NAME
                                ), newFileName
                            )
                            //文件重命名
                            file.renameTo(newFile)
                            val result =
                                NetworkApi.uploadLog(Util.uploadFile(newFile.path, "file/txt"))
                            mUploadLogLiveData.value = result
                        } else {
                            LogUtil.e("${fileName}日志文件不存在")
                        }
                    } catch (e: Exception) {
                        LogUtil.e("日志文件上传错误:${e.message}")
                    }
                }
            }
        }
    }

    /**
     * 上传设备日志
     */
    fun uploadDeviceLog(
        deviceOutId: String, uploadTime: String, macID: String, logFileUrl: String
    ) {
        viewModelScope.launch {
            mMutex.withLock {
                val result = NetworkApi.uploadDeviceLog(deviceOutId, uploadTime, macID, logFileUrl)
                mUploadDeviceLogLiveData.value = result
            }
        }
    }
}