package com.gh.gamecenter.feature.entity

import android.os.Parcel
import android.os.Parcelable
import androidx.annotation.NonNull
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.Ignore
import androidx.room.PrimaryKey
import androidx.room.TypeConverters
import com.therouter.TheRouter
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, CommunityItemData {

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

    @SerializedName("communityId")
    @ColumnInfo(name = "communityId")
    private var _communityId: String? = null // communityId + userId  社区推荐数据库存储专用,社区推荐接口不能给该字段

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

    var orderTag: Long = 0

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

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

    @SerializedName("brief")
    @ColumnInfo(name = "brief")
    private var _brief: String? = null

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

    @TypeConverters(ListStringConverter::class)
    @SerializedName("images")
    @ColumnInfo(name = "images")
    private 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)
    @SerializedName("user")
    @ColumnInfo(name = "user")
    private var _user: UserEntity = UserEntity()

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

    @SerializedName("community_name")
    @ColumnInfo(name = "communityName")
    private var _communityName: String? = null

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

    @SerializedName("active")
    @ColumnInfo(name = "active")
    private var _active: Boolean = true

    @SerializedName("type")
    @ColumnInfo(name = "type")
    private var _type: String = ""

    var time: Long? = 0

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

    @Ignore
    var read: Boolean = true

    @Ignore
    @SerializedName("me")
    @ColumnInfo(name = "me")
    private var _me: MeEntity = MeEntity()

    @Ignore
    @SerializedName("commentable")
    @ColumnInfo(name = "commentable")
    private 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
    @SerializedName("count")
    @ColumnInfo(name = "count")
    private var _count: Count = Count()

    // 有三种状态 pass通过，fail未通过，pending审核中
    @SerializedName("status")
    @ColumnInfo(name = "status")
    private var _status: String = ""

    var content: String = ""

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

    @SerializedName("tag_activity_name")
    @Ignore
    private var _tagActivityName: String = ""

    @SerializedName("sections")
    @Ignore
    private var _sections: List<SectionEntity> = 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() ?: ""
        title = 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(title)
        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 var id: String
        get() = _id ?: ""
        set(value) {
            _id = value
        }

    override var type: String
        get() = _type
        set(value) {
            _type = value
        }

    override var active: Boolean
        get() = _active
        set(value) {
            _active = value
        }

    override var commentable: Boolean
        get() = _commentable
        set(value) {
            _commentable = value
        }

    override var me: MeEntity
        get() = _me
        set(value) {
            _me = value
        }

    override var count: Count
        get() = _count
        set(value) {
            _count = value
        }

    override var community: CommunityEntity
        get() = bbs
        set(value) {
            bbs = value
        }

    override var title: String
        get() = articleTitle ?: ""
        set(value) {
            articleTitle = value
        }

    override var brief: String
        get() = _brief ?: ""
        set(value) {
            _brief = value
        }

    override var images: List<String>
        get() = _images
        set(value) {
            _images = value
        }

    override var user: UserEntity
        get() = _user
        set(value) {
            _user = value
        }

    override var status: String
        get() = _status
        set(value) {
            _status = value
        }

    override var questions: Questions
        get() = _questions
        set(value) {
            _questions = value
        }

    override var tagActivityName: String
        get() = _tagActivityName
        set(value) {
            _tagActivityName = value
        }

    override var sections: List<SectionEntity>
        get() = _sections
        set(value) {
            _sections = value
        }

    override var communityId: String?
        get() = _communityId
        set(value) {
            _communityId = value
        }

    override var communityName: String?
        get() = _communityName
        set(value) {
            _communityName = value
        }

    override fun describeContents(): Int {
        return 0
    }

    fun transformForumVideoEntity(): ForumVideoEntity {
        val forumVideoEntity = ForumVideoEntity()
        if (type.contains("video")) {
            forumVideoEntity.id = id
            forumVideoEntity.title = title
            forumVideoEntity.des = des
            forumVideoEntity.url = url
            forumVideoEntity.status = status
            forumVideoEntity.poster = poster
            forumVideoEntity.length = length
            forumVideoEntity.duration = TimeUtils.formatVideoDuration(length)
            forumVideoEntity.videoInfo = videoInfo
            forumVideoEntity.bbs = community
            forumVideoEntity.user = user
            forumVideoEntity.tagActivityName = tagActivityName
            forumVideoEntity.sections = sections
            forumVideoEntity.videoIsMuted = SPUtils.getBoolean(Constants.SP_VIDEO_PLAY_MUTE, true)
            forumVideoEntity.type = type
        } else {
            forumVideoEntity.title = questions.title ?: ""
            forumVideoEntity.des = brief ?: ""
            forumVideoEntity.user = user
            forumVideoEntity.bbs = community
            forumVideoEntity.tagActivityName = tagActivityName
            forumVideoEntity.sections = sections
            forumVideoEntity.type = type
            forumVideoEntity.videoIsMuted = SPUtils.getBoolean(Constants.SP_VIDEO_PLAY_MUTE, true)
            val userManagerProvider = TheRouter.get(IUserManagerProvider::class.java)
            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 = brief.ifEmpty { description ?: "" }
        articleEntity.title = title
        articleEntity.images = images
        articleEntity.videos = videos
        articleEntity.user = user
        articleEntity.time = TimeEntity(time = time ?: 0, create = 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.community = 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
        articleEntity.sections = sections
        articleEntity.tagActivityName = tagActivityName
        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)
            }
        }
    }

}