package com.rv.im.view;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.support.annotation.NonNull;
import android.support.design.widget.TabLayout;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;

import com.rv.im.R;
import com.rv.im.util.SmileyParser;

import java.lang.ref.SoftReference;


/**
 * 表情界面
 *
 * @author Administrator
 */
public class ChatFaceView extends RelativeLayout {
    private Context mContext;
    private ViewPager mViewPager;

    private EmotionClickListener mEmotionClickListener;

    public ChatFaceView(Context context) {
        super(context);
        init(context);
    }

    public ChatFaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initAttrs(attrs);
        init(context);
    }

    public ChatFaceView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initAttrs(attrs);
        init(context);
    }

    private static int dip_To_px(Context context, int dipValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dipValue * scale + 0.5f);
    }

    private void initAttrs(AttributeSet attrs) {
        if (attrs == null) {
            return;
        }
        TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ChatFaceView);// TypedArray是一个数组容器
        a.recycle();
    }

    @SuppressWarnings("deprecation")
    private void init(Context context) {
        mContext = context;
        LayoutInflater.from(mContext).inflate(R.layout.chat_face_view, this);
        mViewPager = findViewById(R.id.view_pager);
        ((TabLayout) findViewById(R.id.tabDots)).setupWithViewPager(mViewPager, false);
        switchViewPager();
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
    }


    public void setEmotionClickListener(EmotionClickListener listener) {
        mEmotionClickListener = listener;
    }

    public interface EmotionClickListener {
        void onNormalFaceClick(SpannableString ss);

    }

    interface OnEmojiClickListener {
        void onEmojiClick(SpannableString ss);
    }


    static class EmojiAdapter extends BaseAdapter {
        private final Context ctx;
        private final int[] idList;

        EmojiAdapter(Context ctx, int[] idList) {
            this.ctx = ctx;
            this.idList = idList;
        }

        @Override
        public int getCount() {
            return idList.length;
        }

        @Override
        public Object getItem(int position) {
            return idList[position];
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) {
                convertView = new ImageView(ctx);
                // 宽高间距计算保留旧代码，
                AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                convertView.setLayoutParams(layoutParams);
                convertView.setPadding(dip_To_px(ctx, 13), dip_To_px(ctx, 7), 0, 0);
            }
            ImageView ivEmoji = (ImageView) convertView;
            int res = idList[position];
            ivEmoji.setImageResource(res);
            return convertView;
        }
    }

    /*
   Emotion
    */
    private void switchViewPager() {
        mViewPager.setAdapter(new EmojiPager1Adapter(
                getContext(),
                SmileyParser.Smilies.getIds(),
                SmileyParser.Smilies.getTexts(),
                ss -> {
                    mEmotionClickListener.onNormalFaceClick(ss);
                }
        ));
    }

    static class EmojiPager1Adapter extends PagerAdapter {
        // 弱引用缓存表情第一页，用来加速加载，
        private static SoftReference<GridView> softFirstPage = new SoftReference<>(null);
        private int[][] idMatrix;
        // 表情符号所代表的英文字符
        private String[][] strMatrix;
        private OnEmojiClickListener listener;
        private Context ctx;

        EmojiPager1Adapter(Context ctx, int[][] idMatrix, String[][] strMatrix, OnEmojiClickListener listener) {
            this.ctx = ctx;
            this.idMatrix = idMatrix;
            this.strMatrix = strMatrix;
            this.listener = listener;
        }

        @Override
        public int getCount() {
            return idMatrix.length;
        }

        @Override
        public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
            container.removeView((View) object);
        }

        @NonNull
        @Override
        public Object instantiateItem(@NonNull ViewGroup container, int pagePosition) {
            int[] idList = idMatrix[pagePosition];
            String[] strList = strMatrix[pagePosition];
            GridView gridView = null;
            if (0 == pagePosition) {
                gridView = softFirstPage.get();
            }
            if (gridView == null) {
                gridView = (GridView) LayoutInflater.from(ctx).inflate(R.layout.emotion_gridview, container, false);
                gridView.setSelector(R.drawable.chat_face_bg);
                ListAdapter adapter = new EmojiAdapter(ctx, idList);
                gridView.setAdapter(adapter);
                gridView.setPadding(0, 0, dip_To_px(ctx, 12), 0);
                if (0 == pagePosition) {
                    softFirstPage = new SoftReference<>(gridView);
                }
            }
            container.addView(gridView);
            gridView.setOnItemClickListener((parent, view, itemPosition, id) -> {
                if (listener != null) {
                    int res = idList[itemPosition];
                    String text = strList[itemPosition];
                    SpannableString ss = new SpannableString(text);
                    Drawable d = ctx.getResources().getDrawable(res);
                    // 设置表情图片的显示大小
                    d.setBounds(0, 0, (int) (d.getIntrinsicWidth() / 1.95), (int) (d.getIntrinsicHeight() / 1.95));
                    ImageSpan span = new ImageSpan(d, ImageSpan.ALIGN_BOTTOM);
                    ss.setSpan(span, 0, text.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    listener.onEmojiClick(ss);
                }
            });
            return gridView;
        }

        @Override
        public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
            return view == object;
        }
    }
}
