package com.yidian.yac.newscontent.adapter

import android.annotation.SuppressLint
import android.content.Intent
import android.view.Gravity
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
import com.yidian.chameleon.ChameleonParser
import com.yidian.common.Constants
import com.yidian.common.utils.ViewHolderUtil.Companion.createItemView
import com.yidian.yac.newscontent.R
import com.yidian.yac.newscontent.app.NewsContentApplication
import com.yidian.yac.newscontent.bean.SimpleItemBean
import com.yidian.yac.newscontent.ui.NewsContentActivity
import kotlinx.android.extensions.LayoutContainer
import kotlinx.android.synthetic.main.item_home_simple.*
import org.json.JSONArray
import org.json.JSONObject
import java.io.BufferedReader
import java.io.InputStreamReader

class SimpleHomeAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
    private val TAG = "SimpleHomeAdapter"
    private val dataList: ArrayList<SimpleItemBean> by lazy { ArrayList<SimpleItemBean>() }
    private lateinit var chameleonParser: ChameleonParser
    private var configs: JSONArray = createChameleonConfig()
    private var dataJson: JSONObject = createJsonData()

    private fun createJsonData(): JSONObject {
        val openIs =
            NewsContentApplication.context.resources.assets.open("chameleon/data.json")
        val bufferedReader =
            BufferedReader(InputStreamReader(openIs))

        val content = StringBuilder()
        var line: String?
        while (bufferedReader.readLine().also { line = it } != null) {
            content.append(line).append('\n')
        }

        bufferedReader.close()

        return JSONObject(content.toString().trim())
    }

    private fun createChameleonConfig(): JSONArray {

        val openIs =
            NewsContentApplication.context.resources.assets.open("chameleon/rules.json")
        val bufferedReader =
            BufferedReader(InputStreamReader(openIs))

        val content = StringBuilder()
        var line: String?
        while (bufferedReader.readLine().also { line = it } != null) {
            content.append(line).append('\n')
        }

        bufferedReader.close()

        return JSONArray(content.toString().trim())
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
        return if (viewType == 0) {
            ViewHolder(createItemView(parent, R.layout.item_home_simple))

        } else {

            ChameleonViewHolder(createChameleonView(parent, viewType))
        }

    }


    override fun getItemCount(): Int {
        return dataList.size
    }

    override fun getItemViewType(position: Int): Int {
        return dataList[position].itemType
    }

    private fun createChameleonView(parent: ViewGroup, viewType: Int): View {
        if (!this::chameleonParser.isInitialized) {
            chameleonParser = ChameleonParser(parent.context)
        }
        for (i in 0 until configs.length()){
            val templeBean = configs.optJSONObject(i)
            if (templeBean.optString(Constants.CHAMELEON_D_TYPE).toInt() == viewType )
            return chameleonParser.createView(templeBean.optString(Constants.CHAMELEON_ID))
        }
        return createEmptyView(parent)
    }

    private fun createEmptyView(parent: ViewGroup): View {
        val textView = TextView(parent.context)
        textView.textSize = 16f
        textView.gravity = Gravity.CENTER
        textView.text = "无法解析Chameleon"
        val params = FrameLayout.LayoutParams(120, 120)
        textView.layoutParams = params
        return textView
    }

    override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
        holder.itemView.setOnClickListener {
            it.context.startActivity(Intent(it.context, NewsContentActivity::class.java))
        }
        if (getItemViewType(position) == 0) {
            holder as ViewHolder
            holder.setData(dataList[position])
            return
        }
        holder as ChameleonViewHolder
        if (holder.itemView is TextView) return
        chameleonParser.bindTemplateData(holder.itemView, dataJson)
    }


    fun setData(list: ArrayList<SimpleItemBean>?) {
        list?.let {
            dataList.clear()
            dataList.addAll(it)
            notifyDataSetChanged()
        }
    }

    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView), LayoutContainer {
        override val containerView: View?
            get() = itemView

        @SuppressLint("SetTextI18n")
        fun setData(simpleItemBean: SimpleItemBean) {
            tv_itemHomeName.text = "卡片 $adapterPosition ${simpleItemBean.name}"
            tv_itemHomeContent.text = "Native 卡片"

        }
    }

    class ChameleonViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}