package com.atmob.keyboard_android.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.atmob.keyboard_android.R;


/**
 * 支持IconFont的TextView
 */
public class IconFontTextView extends TextView {
    /**
     * App图标
     */
    private static final int TYPEFACE_CODE_APP = 1;

    private Typeface ttfTypeface = null;

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

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

    public IconFontTextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs, defStyleAttr, 0);
    }

    private void init(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.IconFontTextView, defStyleAttr, defStyleRes);
        int typefaceCode = typedArray.getInt(R.styleable.IconFontTextView_ift_typeface, TYPEFACE_CODE_APP);
        int textStyle = typedArray.getInt(R.styleable.IconFontTextView_android_textStyle, Typeface.NORMAL);

        //加载字体文件
        Typeface baseTypeface;
        if (typefaceCode == TYPEFACE_CODE_APP) {
            baseTypeface = getTypeface(context, "fonts/app_font.ttf");
        } else {
            throw new IllegalArgumentException("字体非法");
        }

        // 合并用户设置的 textStyle，例如设置斜体
        if (baseTypeface != null) {
            Typeface styledTypeface = Typeface.create(baseTypeface, textStyle);
            setTypeface(styledTypeface);
        }

        // 去掉padding,这样IconFont和普通字体容易对齐
        setIncludeFontPadding(false);

        typedArray.recycle();
    }

    public synchronized Typeface getTypeface(Context context, String path) {
        if (ttfTypeface == null) {
            try {
                ttfTypeface = Typeface.createFromAsset(context.getAssets(), path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return ttfTypeface;
    }

    public synchronized void clearTypeface() {
        ttfTypeface = null;
    }
}