package com.sheep.gamegroup.util;

import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.Html;
import android.text.Spanned;
import android.text.style.ClickableSpan;
import android.text.style.ImageSpan;
import android.view.View;

import org.xml.sax.XMLReader;

import java.util.ArrayList;
import java.util.Locale;

/**
 * Created by realicing on 2018/11/20.
 * realicing@sina.com
 * 图片处理类
 */
public class DetailTagHandler implements Html.TagHandler {
    private ArrayList<String> strings;

    public DetailTagHandler() {
        strings = new ArrayList<>();
    }

    @Override
    public void handleTag(boolean opening, String tag, Editable output, XMLReader xmlReader) {
        // 处理标签<img>
        if ("img".equals(tag.toLowerCase(Locale.getDefault()))) {
            // 获取长度
            int len = output.length();
            // 获取图片地址
            ImageSpan[] images = output.getSpans(len - 1, len, ImageSpan.class);
            String imgURL = images[0].getSource();
            if(imgURL != null && (imgURL.startsWith("http://") || imgURL.startsWith("https://"))) {
                // 记录所有图片地址
                strings.add(imgURL);
                // 记录是第几张图片
                int position = strings.size() - 1;
                // 使图片可点击并监听点击事件
                output.setSpan(new ClickableImage(position), len - 1, len,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }

    public void clear() {
        strings.clear();
    }

    private class ClickableImage extends ClickableSpan {
        private int position;

        private ClickableImage(int position) {
            this.position = position;
        }

        @Override
        public void onClick(@NonNull View widget) {
            Jump2View.getInstance().showImgList(ActivityManager.getInstance().currentActivity(), position, strings);
        }
    }
}