package com.gh.gamecenter.feature.entity

import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.NonNull
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.alibaba.android.arouter.launcher.ARouter
import com.gh.gamecenter.common.annotation.SyncIgnore
import com.gh.gamecenter.common.annotation.SyncPage
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.constant.RouteConsts
import com.gh.gamecenter.common.entity.CommunityEntity
import com.gh.gamecenter.common.syncpage.SyncFieldConstants
import com.gh.gamecenter.core.provider.IUserManagerProvider
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.core.utils.TimeUtils
import com.gh.gamecenter.feature.room.converter.*
import com.google.gson.annotations.SerializedName

/**
 * Created by khy on 12/12/17.
 */
@Entity
class AnswerEntity() : Parcelable {

    @NonNull
    @PrimaryKey
    var primaryKey: String = "" // db key

    var communityId: String? = null // communityId + userId  社区推荐数据库存储专用,社区推荐接口不能给该字段

    @Ignore
    @SerializedName("community_id")
    var articleCommunityId: String = "" // 一般情况,只有该数据是文章时接口才会给该字段

    var orderTag: Long = 0

    @SerializedName("_id")
    var id: String? = null

    @SerializedName("sequence_id")
    var sequenceId: String? = null

    var brief: String? = null

    @SerializedName("title")
    var articleTitle: String? = null

    @TypeConverters(ListStringConverter::class)
    var images: List<String> = ArrayList()

    @TypeConverters(ImageInfoConverter::class)
    @SerializedName("images_info")
    var imagesInfo: List<ImageInfo> = ArrayList()

    @TypeConverters(CommunityVideoConverter::class)
    var videos: List<CommunityVideoEntity> = ArrayList()

    @SyncPage(syncNames = [SyncFieldConstants.ANSWER_VOTE_COUNT, SyncFieldConstants.ARTICLE_VOTE_COUNT])
    var vote: Int = 0

    @TypeConverters(AnswerUserConverter::class)
    var user: UserEntity = UserEntity()

    @SyncIgnore // questions里的vote当前entity的vote冲突
    @TypeConverters(QuestionsConverter::class)
    @SerializedName("question")
    var questions: Questions = Questions()

    @SerializedName("community_name")
    var communityName: String? = null

    //    @SyncPage(syncNames = [SyncFieldConstants.ANSWER_COMMENT_COUNT, SyncFieldConstants.ARTICLE_COMMENT_COUNT])
    @SerializedName("comment_count")
    var commentCount: Int = 0

    var active: Boolean = true

    var type: String = ""

    var time: Long? = 0

    @Ignore
    @SerializedName("edit_time")
    var editTime: Long = 0

    @Ignore
    var read: Boolean = true

    @Ignore
    var me: MeEntity = MeEntity()

    @Ignore
    var commentable: Boolean = true

    // 只用于回答草稿列表
    @Ignore
    @SerializedName("answer_id")
    var answerId: String = ""

    @Ignore
    @SyncPage(syncNames = [SyncFieldConstants.ANSWER_COUNT])
    @SerializedName("answer_count")
    var answerCount: Int = 0

    @Ignore
    var bbs: CommunityEntity = CommunityEntity()

    @Ignore
    var description: String? = ""

    @Ignore
    @SerializedName("popular_answer")
    var popularAnswer: AnswerEntity? = null

    var des: String = ""

    var url: String = ""

    @TypeConverters(VideoInfoConverter::class)
    @SerializedName("video_info")
    var videoInfo: VideoInfo = VideoInfo()

    var poster: String = ""

    var length: Long = 0

    @Ignore
    var count: Count = Count()

    // 有三种状态 pass通过，fail未通过，pending审核中
    var status: String = ""

    var content: String = ""

    @Ignore
    @SerializedName("section_id")
    var sectionIdList: List<String> = ArrayList()

    fun getPassVideos(): List<CommunityVideoEntity> {
        val passVideos = arrayListOf<CommunityVideoEntity>()
        for (video in videos) {
            if (video.status == "pass") passVideos.add(video)
        }
        return passVideos
    }

    constructor(parcel: Parcel) : this() {
        primaryKey = parcel.readString() ?: ""
        communityId = parcel.readString() ?: ""
        articleCommunityId = parcel.readString() ?: ""
        orderTag = parcel.readLong()
        id = parcel.readString()
        brief = parcel.readString()
        articleTitle = parcel.readString()
        questions = parcel.readParcelable(Questions::class.java.classLoader) ?: Questions()
        images = parcel.createStringArrayList() ?: arrayListOf()
        commentCount = parcel.readInt()
        vote = parcel.readInt()
        user = parcel.readParcelable(UserEntity::class.java.classLoader) ?: UserEntity()
        communityName = parcel.readString()
        active = parcel.readByte() != 0.toByte()
        type = parcel.readString() ?: ""
        time = parcel.readLong()
        des = parcel.readString() ?: ""
        url = parcel.readString() ?: ""
        videoInfo = parcel.readParcelable(VideoInfo::class.java.classLoader) ?: VideoInfo()
        poster = parcel.readString() ?: ""
        length = parcel.readLong()
        count = parcel.readParcelable(Count::class.java.classLoader) ?: Count()
        status = parcel.readString() ?: ""
        content = parcel.readString() ?: ""
    }

    override fun writeToParcel(parcel: Parcel, flags: Int) {
        parcel.writeString(primaryKey)
        parcel.writeString(communityId)
        parcel.writeString(articleCommunityId)
        parcel.writeLong(orderTag)
        parcel.writeString(id)
        parcel.writeString(brief)
        parcel.writeString(articleTitle)
        parcel.writeParcelable(questions, flags)
        parcel.writeStringList(images)
        parcel.writeInt(vote)
        parcel.writeInt(commentCount)
        parcel.writeParcelable(user, flags)
        parcel.writeString(communityName)
        parcel.writeByte(if (active) 1 else 0)
        parcel.writeString(type)
        parcel.writeLong(time ?: 0)
        parcel.writeString(des)
        parcel.writeString(url)
        parcel.writeParcelable(videoInfo, flags)
        parcel.writeString(poster)
        parcel.writeLong(length)
        parcel.writeParcelable(count, flags)
        parcel.writeString(status)
        parcel.writeString(content)
    }

    override fun describeContents(): Int {
        return 0
    }

    fun transformForumVideoEntity(): ForumVideoEntity {
        val forumVideoEntity = ForumVideoEntity()
        if (type.contains("video")) {
            forumVideoEntity.id = id ?: ""
            forumVideoEntity.title = articleTitle ?: ""
            forumVideoEntity.des = des
            forumVideoEntity.url = url
            forumVideoEntity.status = status
            forumVideoEntity.poster = poster
            forumVideoEntity.length = length
            forumVideoEntity.duration = TimeUtils.formatVideoDuration(length)
            forumVideoEntity.videoInfo = videoInfo
            forumVideoEntity.videoIsMuted = SPUtils.getBoolean(Constants.SP_VIDEO_PLAY_MUTE, true)
        } else {
            forumVideoEntity.title = questions.title ?: ""
            forumVideoEntity.des = brief ?: ""
            forumVideoEntity.videoIsMuted = SPUtils.getBoolean(Constants.SP_VIDEO_PLAY_MUTE, true)
            val userManagerProvider =
                ARouter.getInstance().build(RouteConsts.provider.userManager).navigation() as? IUserManagerProvider
            val newVideos = if (user.id == userManagerProvider?.getUserId()) videos else getPassVideos()
            if (newVideos.isNotEmpty()) {
                forumVideoEntity.id = newVideos[0].id
                forumVideoEntity.url = newVideos[0].url
                forumVideoEntity.poster = newVideos[0].poster
                forumVideoEntity.status = status
                forumVideoEntity.duration = newVideos[0].duration
                forumVideoEntity.videoInfo = VideoInfo(width = newVideos[0].width, height = newVideos[0].height)
            }
        }
        return forumVideoEntity
    }

    fun transformArticleEntity(): ArticleEntity {
        val articleEntity = ArticleEntity()
        articleEntity.id = id ?: ""
        articleEntity.brief = if (!brief.isNullOrEmpty()) brief ?: "" else description ?: ""
        articleEntity.title = articleTitle ?: ""
        articleEntity.images = images
        articleEntity.videos = videos
        articleEntity.user = user
        articleEntity.time = TimeEntity(time ?: 0)
        articleEntity.count = count
        articleEntity.active = active
        articleEntity.orderTag = orderTag
        articleEntity.read = read
        articleEntity.me = me
        articleEntity.commentable = commentable
        articleEntity.community = CommunityEntity(
            bbs.id,
            bbs.name,
            icon = bbs.game?.getIcon(),
            iconSubscript = bbs.game?.iconSubscript,
            game = bbs.game
        )
        articleEntity.bbs = articleEntity.community
        articleEntity.imagesInfo = imagesInfo
        articleEntity.des = des
        articleEntity.url = url
        articleEntity.videoInfo = videoInfo
        articleEntity.poster = poster
        articleEntity.length = length
        articleEntity.type = type
        articleEntity.count = count
        return articleEntity
    }

    companion object {
        const val TAG: String = "AnswerEntity"

        @JvmField
        val CREATOR: Parcelable.Creator<AnswerEntity> = object : Parcelable.Creator<AnswerEntity> {
            override fun createFromParcel(parcel: Parcel): AnswerEntity {
                return AnswerEntity(parcel)
            }

            override fun newArray(size: Int): Array<AnswerEntity?> {
                return arrayOfNulls(size)
            }
        }
    }

}