/**
 * Copyright (C) 2012 - Florindo Smilari (spherIC)
 */
package ch.spherIC.recurvebowsight.components;

import android.content.Context;

import android.content.res.TypedArray;

import android.graphics.Typeface;

import android.util.AttributeSet;
import android.util.Log;

import android.widget.EditText;

import ch.spherIC.recurvebowsight.R;
import ch.spherIC.recurvebowsight.utilities.UnitConverter;


/**
 * Siehe http://stackoverflow.com/questions/2376250/custom-fonts-and-xml-layouts-android.
 *
 * @author  FC Smilari
 */
public class FontEditText extends EditText {

    private static final String TAG = "EditText";

    public FontEditText(final Context context) {
        super(context);
        setTextColor(getResources().getColor(R.color.black));
    }

    public FontEditText(final Context context, final AttributeSet attrs) {
        super(context, attrs);
        setFont(context, attrs);
    }

    public FontEditText(final Context context, final AttributeSet attrs, final int defStyle) {
        super(context, attrs, defStyle);
        setFont(context, attrs);
    }

    private void setFont(final Context ctx, final AttributeSet attrs) {
        if (!isInEditMode()) {
            TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.FontEditText);
            String font = a.getString(R.styleable.FontEditText_txtFont);
            if (font != null && !font.isEmpty()) {
                setFont(ctx, font);
            }
            a.recycle();
        }
        setTextColor(getResources().getColor(R.color.black));
    }

    public boolean setFont(final Context ctx, final String font) {
        Typeface tf = null;
        try {
            tf = Typeface.createFromAsset(ctx.getAssets(), font);
        } catch (final Exception e) {
            Log.e(TAG, "Could not get typeface: " + e.getMessage());
            return false;
        }

        setTypeface(tf);
        return true;
    }

    @Override
    public void setEnabled(final boolean enabled) {
        super.setEnabled(enabled);
        if (enabled) {
            setBackgroundDrawable(getResources().getDrawable(android.R.drawable.edit_text));
            setTextColor(getResources().getColor(R.color.black));
        } else {
            setBackgroundDrawable(getResources().getDrawable(android.R.drawable.editbox_dropdown_light_frame));
            getBackground().setAlpha(255);
            setTextColor(getResources().getColor(R.color.gray_medium));
            setPadding(UnitConverter.dpToPxH(8), getPaddingTop(), getPaddingRight(), getPaddingBottom());
        }
    }

}
