package kr.co.hanwha.hifive.util;

import android.content.Context;
import android.graphics.Typeface;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.StyleSpan;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import kr.co.hanwha.hifive.R;
import kr.co.hanwha.hifive.adapter.contract.TaskDetailListContract;
import kr.co.hanwha.hifive.view.NonUnderlineClickSpan;

/**
 * Created by sanghoonkwon on 2018. 1. 11..
 */

public class HFSpanUtil {
    /**
     * 검색 결과 - SPAN
     *
     * @param context    Context
     * @param textView
     * @param text
     * @param searchWord
     */
    public static void setSearchResult(@NonNull Context context,
                                       @NonNull TextView textView,
                                       @Nullable String text,
                                       @Nullable String searchWord) {
        if (TextUtils.isEmpty(text) == false) {
            int color = HFCommonUtil.getColor(context, R.color.hf_blue02);
            SpannableString styledString = new SpannableString(text);

            if (TextUtils.isEmpty(searchWord) == false) {
                int fromIndex = 0;
                boolean isFinish = false;
                while (!isFinish) {
                    int startPosition = text.indexOf(searchWord, fromIndex);
                    int endPosition = startPosition + searchWord.length();
                    if (startPosition >= 0) {
                        styledString.setSpan(new ForegroundColorSpan(color), startPosition, endPosition, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                        styledString.setSpan(new StyleSpan(Typeface.BOLD), startPosition, endPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                        fromIndex = endPosition;
                    } else {
                        isFinish = true;
                    }
                }
            }
            textView.setText(styledString);
        } else {
            textView.setText("");
        }
    }

    /**
     * 입력시 태그 칼라 셋팅
     *
     * @param context  Context
     * @param editable
     * @return 태그 목록
     */
    public static ArrayList<String> getTagListSetColorSpan(@NonNull Context context, @NonNull Editable editable) {
        String text = editable.toString();
        ArrayList<String> listOfTags = getTagSplitStrings(text);
        for (int i = 0; i < listOfTags.size(); i++) {
            int startPosition = text.indexOf(listOfTags.get(i));
            int endPosition = startPosition + listOfTags.get(i).length();
            String word = listOfTags.get(i);
            if (word.startsWith("#")) {
                int color = HFCommonUtil.getColor(context, R.color.hf_blue02);
                editable.setSpan(new ForegroundColorSpan(color), startPosition, endPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        return listOfTags;
    }

    /**
     * 설명 - 태그 액션 포함 SPAN
     *
     * @param context              Context
     * @param textView             TextView
     * @param message              Message
     * @param onTaskDetailListener
     */

    public static void setDescText(@NonNull Context context,
                                   @NonNull TextView textView,
                                   @Nullable String message,
                                   @Nullable final TaskDetailListContract.OnTaskDetailListener onTaskDetailListener) {
        if (TextUtils.isEmpty(message) == false) {
            String[] links = null;
            try {
                links = HFStringUtil.extractLinks(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
            SpannableString styledString = new SpannableString(message);

            if (links != null) {
                for (int i = 0; i < links.length; i++) {
                    int startPosition = message.indexOf(links[i]);
                    int endPosition = startPosition + links[i].length();

                    final String url = links[i];

                    ClickableSpan clickableURLSpan = new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            if (onTaskDetailListener != null)
                                onTaskDetailListener.onUrlLinkClicked(url);
                        }
                    };
                    styledString.setSpan(clickableURLSpan, startPosition, endPosition, 0);
                }
            }

            // Tag
            ArrayList<String> listOfTags = getTagSplitStrings(message);
            int lastIndex = 0;
            for (int i = 0; i < listOfTags.size(); i++) {
                int startPosition = message.indexOf(listOfTags.get(i), lastIndex);
                int endPosition = startPosition + listOfTags.get(i).length();
                lastIndex = endPosition;

                final String word = listOfTags.get(i);
                if (word.startsWith("#")) {
                    int color = HFCommonUtil.getColor(context, R.color.hf_blue02);
                    NonUnderlineClickSpan clickableSpan = new NonUnderlineClickSpan(color) {
                        @Override
                        public void onClick(View widget) {
                            if (onTaskDetailListener != null) {
                                String searchWord = word.replace("#", "");
                                onTaskDetailListener.onTagClicked(searchWord);
                            }
                        }
                    };

                    styledString.setSpan(clickableSpan, startPosition, endPosition, 0);
                }
            }
            /*
String text = editable.toString();
        ArrayList<String> listOfTags = getTagSplitStrings(text);
        for (int i = 0; i < listOfTags.size(); i++) {
            int startPosition = text.indexOf(listOfTags.get(i));
            int endPosition = startPosition + listOfTags.get(i).length();
            String word = listOfTags.get(i);
            if (word.startsWith("#")) {
                int color = HFCommonUtil.getColor(context, R.color.hf_blue02);
                editable.setSpan(new ForegroundColorSpan(color), startPosition, endPosition, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
             */

            textView.setText(styledString);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            textView.setText("");
        }
    }

    /**
     * 댓글 - 태그 액션 포함 SPAN
     *
     * @param context
     * @param textView
     * @param message
     * @param onTaskDetailListener
     */
    public static void setCommentText(@NonNull Context context,
                                      @NonNull TextView textView,
                                      @Nullable String message,
                                      @Nullable final TaskDetailListContract.OnTaskDetailListener onTaskDetailListener) {
        if (TextUtils.isEmpty(message) == false) {
            String[] links = null;
            try {
                links = HFStringUtil.extractLinks(message);
            } catch (Exception e) {
                e.printStackTrace();
            }

            SpannableString styledString = new SpannableString(message);

            if (links != null) {
                for (int i = 0; i < links.length; i++) {
                    int startPosition = message.indexOf(links[i]);
                    int endPosition = startPosition + links[i].length();

                    final String url = links[i];

                    ClickableSpan clickableURLSpan = new ClickableSpan() {
                        @Override
                        public void onClick(View widget) {
                            if (onTaskDetailListener != null)
                                onTaskDetailListener.onUrlLinkClicked(url);
                        }
                    };
                    styledString.setSpan(clickableURLSpan, startPosition, endPosition, 0);
                }
            }

            // Tag
            ArrayList<String> listOfTags = getTagSplitStrings(message);
            for (int i = 0; i < listOfTags.size(); i++) {
                int startPosition = message.indexOf(listOfTags.get(i));
                int endPosition = startPosition + listOfTags.get(i).length();

                final String word = listOfTags.get(i);
                if (word.startsWith("#")) {
                    int color = HFCommonUtil.getColor(context, R.color.hf_blue02);
                    NonUnderlineClickSpan clickableSpan = new NonUnderlineClickSpan(color) {
                        @Override
                        public void onClick(View widget) {
                            if (onTaskDetailListener != null) {
                                String searchWord = word.replace("#", "");
                                onTaskDetailListener.onTagClicked(searchWord);
                            }
                        }
                    };

                    styledString.setSpan(clickableSpan, startPosition, endPosition, 0);
                }
            }

            textView.setText(styledString);
            textView.setMovementMethod(LinkMovementMethod.getInstance());
        } else {
            textView.setText("");
        }
    }

    private static ArrayList<String> getTagSplitStrings(@Nullable String text) {
        ArrayList<String> list = new ArrayList<>();
        if (TextUtils.isEmpty(text)) return list;

        Pattern pattern = Pattern.compile("([#])([^\\s!\"#$%&'()*+,./:;<=>?@\\\\^`{|}~-]+)");
        Matcher matcher = pattern.matcher(text);
        while (matcher.find()) {
            list.add(text.substring(matcher.start(), matcher.end()));
        }
        System.out.println(matcher.replaceAll(""));

        return list;
    }

}
