package com.bc_chat.im.dataSource

import android.net.Uri
import android.text.TextUtils
import android.util.Base64
import com.bc_chat.bc_base.entity.CollectMessage
import com.bc_chat.bc_base.entity.ListModel
import com.bc_chat.bc_base.http.Encryption
import com.bc_chat.bc_base.http.RetrofitHelper
import com.bc_chat.bc_base.utils.Const
import com.zhaohaoting.framework.ZhtLibrary
import com.zhaohaoting.framework.abs.datasource.RxDataSource
import com.zhaohaoting.framework.abs.entity.ResultEntity
import com.zhaohaoting.framework.mvchelper.mvc.ResponseSender
import com.zhaohaoting.framework.utils.DataCache
import com.zhaohaoting.framework.utils.md5.MD5
import io.reactivex.Flowable
import io.rong.imlib.model.MessageContent
import io.rong.message.ImageMessage
import io.rong.message.SightMessage
import io.rong.message.TextMessage
import io.rong.message.VoiceMessage
import java.io.BufferedOutputStream
import java.io.File
import java.io.FileOutputStream
import java.io.IOException
import java.lang.Exception
import java.util.*

/**
 * author：Created by zhaohaoting on 2019/2/27
 * email：526309416@qq.com
 * desc：收藏
 */
class CollectionDataSource : RxDataSource<CollectMessage, ListModel<CollectMessage>>() {

    override fun loadListFromNetWork(params: HashMap<String, Any?>): Flowable<ResultEntity<ListModel<CollectMessage>>>? {
        return RetrofitHelper.api.collectList(Encryption.encryption(params)).map {
            val resultEntity: ResultEntity<ListModel<CollectMessage>> = ResultEntity()
            resultEntity.data = ListModel()
            resultEntity.error = it.error
            resultEntity.message = it.message
            if (it.data ==null)return@map resultEntity
            it.data.list.forEach {
                var message: MessageContent? = null
                when {
                    it.type == Const.CollectionType.TYPE_TEXT_MESSAGE -> message = TextMessage(it.content?.toByteArray())
                    it.type == Const.CollectionType.TYPE_IMAGE_MESSAGE -> {
                        message = ImageMessage(it.content?.toByteArray())
                        parseImage(it.id!!, message)
                    }
                    it.type == Const.CollectionType.TYPE_VOICE_MESSAGE -> {
                        message = VoiceMessage(it.content?.toByteArray())
                        parseVoice(it.id!!, message)
                    }
                    else -> {
                        message = SightMessage(it.content?.toByteArray())
                        parseSight(it.id!!, message)
                    }
                }
                val collectMessage = CollectMessage(it.id)
                collectMessage.content = message
                collectMessage.c_time = it.c_time
                collectMessage.type = it.type
                resultEntity.data.list.add(collectMessage)
            }
            return@map resultEntity
        }
    }

    /**
     * 判断是否还有下一页
     */
    override fun requestSuccess(sender: ResponseSender<ListModel<CollectMessage>>?, dataSource: ListModel<CollectMessage>?) {
        currentTotal = dataSource?.list!!.size
        super.requestSuccess(sender, dataSource)
    }

    /**
     * 解析语言
     */
    private fun parseVoice(id: Int, message: VoiceMessage) {
        try {
            val base64 = message.base64
            val fileName = MD5.getStringMD5(id.hashCode().toString() + "_voice_collection") + ".amr"
            var file = File(DataCache.getVoiceCacheDir(ZhtLibrary.getContext()) + fileName)
            if (!TextUtils.isEmpty(base64) && !file.exists()) {
                try {
                    val data = Base64.decode(base64, Base64.NO_WRAP)
                    file = saveFile(data, DataCache.getVoiceCacheDir(ZhtLibrary.getContext()), fileName)
                } catch (var7: IllegalArgumentException) {
                    var7.printStackTrace()
                } catch (var8: IOException) {
                    var8.printStackTrace()
                }
            }
            message.uri = Uri.fromFile(file)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    @Throws(IOException::class)
    private fun saveFile(data: ByteArray, path: String, fileName: String): File {
        var file = File(path)
        if (!file.exists()) {
            file.mkdirs()
        }

        file = File(path + fileName)
        val bos = BufferedOutputStream(FileOutputStream(file))
        bos.write(data)
        bos.flush()
        bos.close()
        return file
    }

    /**
     * 解析视频
     */
    private fun parseSight(id: Int, message: SightMessage) {
        try {
            val base64 = message.base64
            val fileName = MD5.getStringMD5(id.hashCode().toString() + "_sight_collection") + ".jpg"
            var file = File(DataCache.getPicCacheDir(ZhtLibrary.getContext()) + fileName)
            if (!TextUtils.isEmpty(base64) && !file.exists()) {
                try {
                    val data = Base64.decode(base64, Base64.NO_WRAP)
                    file = saveFile(data, DataCache.getPicCacheDir(ZhtLibrary.getContext()), fileName)
                } catch (var7: IllegalArgumentException) {
                    var7.printStackTrace()
                } catch (var8: IOException) {
                    var8.printStackTrace()
                }
            }
            message.thumbUri = Uri.fromFile(file)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    /**
     * 解析图片
     */
    private fun parseImage(id: Int, message: ImageMessage) {
        try {
            val base64 = message.base64
            val fileName = MD5.getStringMD5(id.hashCode().toString() + "_image_collection") + ".jpg"
            var file = File(DataCache.getPicCacheDir(ZhtLibrary.getContext()) + fileName)
            if (!TextUtils.isEmpty(base64) && !file.exists()) {
                try {
                    val data = Base64.decode(base64, Base64.NO_WRAP)
                    file = saveFile(data, DataCache.getPicCacheDir(ZhtLibrary.getContext()), fileName)
                } catch (var7: IllegalArgumentException) {
                    var7.printStackTrace()
                } catch (var8: IOException) {
                    var8.printStackTrace()
                }
            }
            message.thumUri = Uri.fromFile(file)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}
