package com.efounder.chat.widget;

import android.content.Context;
import android.content.Intent;
import android.text.Layout;
import android.text.Selection;
import android.text.Spannable;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.style.ClickableSpan;
import android.text.style.URLSpan;
import android.text.util.Linkify;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.widget.TextView;

import com.efounder.chat.activity.ChatWebViewActivity;

/**
 * 支持富文本urld的textview
 *
 * @author YQS
 *  * @see com.efounder.widget.skinview.SkinCustomViewInflater
 */
public class ChatTextView extends SkinChatTextView {
    private long mLastActionDownTime = -1;
    private Context mContext;
    //todo 如果修改此类的路径 一定要修改 SkinCustomViewInflater
    public ChatTextView(Context context) {
        super(context);
        mContext = context;
        this.setAutoLinkMask(Linkify.WEB_URLS);
    }


    public ChatTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
        this.setAutoLinkMask(Linkify.WEB_URLS);

    }

    public ChatTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        this.setAutoLinkMask(Linkify.WEB_URLS);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        super.setText(text, type);
        if (getText() instanceof Spannable) {
            URLSpan[] urlSpans = (((Spannable) getText()).getSpans(0, getText().length() - 1, URLSpan.class));
            for (URLSpan urlSpan : urlSpans) {
                String url = urlSpan.getURL();
                int start = ((Spannable) getText()).getSpanStart(urlSpan);
                int end = ((Spannable) getText()).getSpanEnd(urlSpan);
                NoUnderlineSpan noUnderlineSpan = new NoUnderlineSpan(url);

                //我们需要用setSpan（）加入我们自己的跨度之前删除原来的URLSpan
                ((Spannable) getText()).removeSpan(urlSpan);
                Spannable s = (Spannable) getText();
                s.setSpan(noUnderlineSpan, start, end, Spanned.SPAN_POINT_MARK);
            }
        }

    }

    public class NoUnderlineSpan extends URLSpan {
        private String url;

        public NoUnderlineSpan(String url) {
            super(url);
            this.url = url;
        }

        @Override
        public void onClick(View widget) {
            Intent intent = new Intent(mContext, ChatWebViewActivity.class);
            intent.putExtra("url", url);
            mContext.startActivity(intent);
        }

        @Override
        public void updateDrawState(TextPaint ds) {
            ds.setColor(ds.linkColor);
            ds.setUnderlineText(false);
        }
    }

//    @Override
//    public boolean onTouchEvent(MotionEvent event) {
//        CharSequence text = getText();
//        if (text != null && text instanceof Spannable) {
//           return handleLinkMovementMethod(this, (Spannable) text, event);
//        }
//        return super.onTouchEvent(event);
//
//    }


    private boolean handleLinkMovementMethod(TextView widget, Spannable buffer, MotionEvent event) {

        int action = event.getAction();
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN) {
            int x = (int) event.getX();
            int y = (int) event.getY();
            x -= widget.getTotalPaddingLeft();
            y -= widget.getTotalPaddingTop();

            x += widget.getScrollX();
            y += widget.getScrollY();

            Layout layout = widget.getLayout();
            int line = layout.getLineForVertical(y);

            int off = layout.getOffsetForHorizontal(line, x);

            ClickableSpan[] link = buffer.getSpans(off, off, ClickableSpan.class);


            if (link.length != 0) {

                if (action == MotionEvent.ACTION_UP) {

                    long actionUpTime = System.currentTimeMillis();

                    if (actionUpTime - mLastActionDownTime > ViewConfiguration.getLongPressTimeout()) { //长按事件，取消LinkMovementMethod处理，即不处理ClickableSpan点击事件

                        return false;

                    }

                    link[0].onClick(widget);

                    Selection.removeSelection(buffer);

                } else if (action == MotionEvent.ACTION_DOWN) {

                    try {
                        Selection.setSelection(buffer, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    mLastActionDownTime = System.currentTimeMillis();

                }

            }

        }


        return false;

    }
}
