package lijin.heinika.cn.mygankio.parser

import android.annotation.SuppressLint
import android.content.Context
import android.text.SpannableString
import android.text.method.LinkMovementMethod
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView

import com.bumptech.glide.Glide

import org.jsoup.Jsoup
import org.jsoup.helper.StringUtil
import org.jsoup.nodes.Document
import org.jsoup.nodes.Element
import org.jsoup.nodes.Node

import java.util.ArrayList

import lijin.heinika.cn.mygankio.utils.SpanUtils

/**
 * Created by yun on 2017/9/16.
 * ul解析
 */

class ULParser : BaseParser() {
    private val TAG = ULParser::class.java.simpleName

    @SuppressLint("SetTextI18n")
    override fun parse(node: Node, context: Context): List<View>? {
        val lists = ArrayList<View>()
        Log.i(TAG, "parse: " + node.toString())
        for (n in node.childNodes()) {
            val content = StringBuilder()
            var html = ""
            var src = ""
            val document = Jsoup.parse(n.toString())
            if (document.getElementsByTag("li").size != 0) {
                val a = document.getElementsByTag("a")[0]
                content.append(a.text()).append("\n")
                html = a.attr("href")
                Log.i(TAG, "html:$html")
                if (document.getElementsByTag("img").size != 0) {
                    val img = document.getElementsByTag("img")[0]
                    src = img.attr("src")
                    Log.i(TAG, "src:$src")
                }
            }
            if (!StringUtil.isBlank(content.toString())) {
                val textView = TextView(context)
                val spannableString = SpanUtils.getULSpannableString(content.toString(), html)
                textView.text = spannableString
                textView.movementMethod = LinkMovementMethod.getInstance()
                lists.add(textView)
                if (!StringUtil.isBlank(src)) {
                    val imageView = ImageView(context)
                    imageView.layoutParams = LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                    Glide.with(context).load(src).into(imageView)
                    lists.add(imageView)
                }
            }
        }
        return lists
    }
}
