/* 
 * Copyright 2015 by AVM GmbH <info@avm.de>
 *
 * This software contains free software; you can redistribute it and/or modify 
 * it under the terms of the GNU General Public License ("License") as 
 * published by the Free Software Foundation  (version 3 of the License). 
 * This software is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the copy of the 
 * License you received along with this software for more details.
 */

package de.avm.fundamentals.views;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.TextView;
import de.avm.fundamentals.R;

import java.io.*;

public class IconView extends TextView {
    private static final String VERSION_PREFERENCES = "versioning_preferences";
    public static final String FONT_AVM = "avm_icon_font2.ttf";
    private static final String VERSION = "version";

    private static Typeface mFont;
    private String mIcon;
    private boolean mIsRotating;

    public IconView(Context context) {
        super(context);
        if (!isInEditMode())
            setTypeface(getTypefaceFromFile(context));
    }

    private static Typeface getTypefaceFromFile(Context context) {
        if(mFont == null) {
            File font = new File(context.getFilesDir(), FONT_AVM);
            if (isAppUpdated(context) || !font.exists()) {
                copyFontToInternalStorage(context, font);
            }
            mFont = Typeface.createFromFile(font);
        }
        return mFont;
    }

    private static boolean isAppUpdated(Context context) {
        SharedPreferences sharedPreferences = context.getSharedPreferences(VERSION_PREFERENCES, Context.MODE_PRIVATE);
        int oldVersion = sharedPreferences.getInt(VERSION, 0);
        int newVersion = getCurrentAppVersion(context);
        if(oldVersion < newVersion) {
            SharedPreferences.Editor edit = sharedPreferences.edit();
            edit.putInt(VERSION, newVersion);
            edit.apply();
            return true;
        }
        return false;
    }

    private static int getCurrentAppVersion(Context context) {
        try {
            return context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 0;
    }

    private static void copyFontToInternalStorage(Context context, File font) {
        try {
            InputStream is = context.getResources().openRawResource(R.raw.avm_icon_font);
            byte[] buffer = new byte[4096];
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(font));
            int readByte;
            while ((readByte = is.read(buffer)) > 0) {
                bos.write(buffer, 0, readByte);
            }
            bos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public IconView(Context context, AttributeSet attrs) {
        super(context, attrs);
        applyAttributes(context, attrs);

        if (!isInEditMode()) {
            setTypeface(getTypefaceFromFile(context));
            setText(mIcon);

            if (mIsRotating) {
                final Animation animation = AnimationUtils.loadAnimation(getContext(), R.anim.rotate_animation);
                startAnimation(animation);
            }
        }
    }

    private void applyAttributes(Context context, AttributeSet attrs) {
        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.IconView, 0, 0);
        try {
            mIcon = a.getString(R.styleable.IconView_iconn);
            mIsRotating = a.getBoolean(R.styleable.IconView_rotating, false);
        } finally {
            a.recycle();
        }
    }

    public void setIcon(final String icon) {
        setText(icon);
    }

    public void setIcon(final int iconResId) {
        setText(getContext().getString(iconResId));
    }
}
