package com.lqr.emoji;

import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.sheep.gamegroup.view.adapter.ArrayAdapter;
import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

/**
 * CSDN_LQR
 * 表情布局
 */
public class EmotionLayout extends LinearLayout implements View.OnClickListener {

    public static int EMOJI_COLUMNS = 3;
    public static int EMOJI_ROWS = 3;
    public static int EMOJI_PER_PAGE = EMOJI_COLUMNS * EMOJI_ROWS;

    private Context mContext;
    private ViewPager mVpEmotioin;
    private LinearLayout mLlPageNumber;

    private IEmotionSelectedListener mEmotionSelectedListener;

    public EmotionLayout(Context context) {
        this(context, null);
    }

    public EmotionLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public EmotionLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        mContext = context;
    }

    public void setEmotionSelectedListener(IEmotionSelectedListener emotionSelectedListener) {
        if (emotionSelectedListener != null) {
            this.mEmotionSelectedListener = emotionSelectedListener;
        } else {
            Log.i("CSDN_LQR", "IEmotionSelectedListener is null");
        }
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        init();
        initListener();
    }

    private void init() {
        LayoutInflater.from(mContext).inflate(R.layout.emotion_layout, this);
        mVpEmotioin = findViewById(R.id.vpEmotioin);
        mLlPageNumber = findViewById(R.id.llPageNumber);

        initViews();
        mVpEmotioin.setAdapter(new ListPagerAdapter(viewList));

    }

    private List<View> viewList;
    private List<View> dianViewList;

    private void initViews() {
        int totalCount = PNG_NAMES.length;
        int pageTotal = (totalCount - 1) / EMOJI_PER_PAGE + 1;
        int perPageCount = EMOJI_PER_PAGE;
        viewList = new ArrayList<>(pageTotal);
        dianViewList = new ArrayList<>(pageTotal);
        for (int i = 0; i < pageTotal; i++) {
            //组装图片数据
            List<String> pngList = new ArrayList<>(perPageCount);
            for (int j = 0; j < perPageCount; j++) {
                int index = i * ( perPageCount - 1) + j;
                if (index + 1 >= totalCount) {
                    break;
                }
                pngList.add(PNG_NAMES[index]);
            }
            //添加每页GridView
            View itemView = LayoutInflater.from(SheepApp.getInstance()).inflate(R.layout.emotion_item_page, null);
            GridView gridView = itemView.findViewById(R.id.emotion_item_page_gv);
            gridView.setNumColumns(EMOJI_COLUMNS);
            gridView.setAdapter(new ArrayAdapter<String>(mContext, R.layout.emotion_item, pngList) {
                @Override
                public boolean convert(int position, View convertView, ViewGroup parent, String item) {
                    ImageView imageView = convertView.findViewById(R.id.emotion_item_iv);
                    if (imageView != null) {
                        imageView.setTag(item);
                        imageView.setImageResource(mContext.getResources().getIdentifier(item, "mipmap", BuildConfig.APPLICATION_ID));
                        imageView.setOnClickListener(EmotionLayout.this);
                    }
                    return true;
                }
            });
            viewList.add(itemView);

            //tabs
            View dianView = View.inflate(mContext, R.layout.emotion_dian, null);
            int radius = getResources().getDimensionPixelSize(R.dimen.content_padding_10);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(radius, radius);
            if (i != 0)
                layoutParams.leftMargin = radius;
            mLlPageNumber.addView(dianView, layoutParams);
            dianViewList.add(dianView);
            dianViewList.get(i).setEnabled(i == 0);
        }
    }

    private void initListener() {

        mVpEmotioin.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < dianViewList.size(); i++) {
                    dianViewList.get(i).setEnabled(i == position);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

    }

    @Override
    public void onClick(View v) {
        Object tag = v.getTag();
        if (tag instanceof String) {
            selectEmotionItem(tag.toString());
        }
    }

    private void selectEmotionItem(String name) {
        if (mMessageEditText != null) {
            mMessageEditText.append(String.format(Locale.CHINA, "[%s]", nameToTagMap.get(name)));
        }
    }


    EditText mMessageEditText;

    public void attachEditText(EditText messageEditText) {
        mMessageEditText = messageEditText;
    }



    public static final String[] PNG_NAMES = {"exp_666", "exp_ccc", "exp_ggl", "exp_hjz", "exp_kbjbg", "exp_lll", "exp_sxyj", "exp_wxll", "exp_xq", "exp_yd", "exp_yx"};
    public static final String[] PNG_TAGS = {"666", "戳", "尴尬了", "好紧张", "苦逼加班狗", "略略略~", "伤心欲绝", "我心凉凉", "嫌弃", "悠闲", "有毒"};
    public static final Map<String, String> nameToTagMap = new HashMap<>();
    public static final Map<String, String> tagToNameMap = new HashMap<>();
    static {
        for (int i = 0; i < PNG_NAMES.length; i++) {
            nameToTagMap.put(PNG_NAMES[i], PNG_TAGS[i]);
            tagToNameMap.put(PNG_TAGS[i], PNG_NAMES[i]);
        }
    }
    //转换内容
    public static String changeContent(String content) {
        for (String pngTag : PNG_TAGS) {
            String replaceContent = String.format(Locale.CHINA, "<img src=\"%s\" />", tagToNameMap.get(pngTag));
            content = content.replaceAll(String.format(Locale.CHINA, "\\[%s\\]", pngTag), replaceContent);
        }
        content = content.replaceAll("\n", "<br>");//替换换行
        return content;
    }
    //转换内容
    public static boolean hasExp(String content) {
        if(content != null && content.contains("[")) {
            for (String pngTag : PNG_TAGS) {
                if (content.contains(String.format(Locale.CHINA, "[%s]", pngTag))) {
                    return true;
                }
            }
        }
        return false;
    }
}
