package com.excelliance.open;

import android.app.Activity;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.util.Log;

import java.lang.reflect.Method;

public class BaseActivity extends Activity {
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(new LebianContext(newBase,getLBTheme(),createResources(newBase)));
    }

    /**
     * int theme = r.activityInfo.getThemeResource();
     * if (theme != 0) {
     *     activity.setTheme(theme);
     * }
     */
    @Override
    public void setTheme(int theme) {
        super.setTheme(getLBTheme());
    }

    public Resources createResources(Context base) {
        try {
            Class<?> cls = BwbxUI.getClass("main.PlatformResources");
            return (Resources) cls.getMethod("getMainResources", Context.class).invoke(null,base);
        } catch (Exception e) {
            e.printStackTrace();
            Log.d("Lebian.BaseActivity","onCreateResource error"+e);
        }
//        return createNewResource(base,base.getApplicationInfo().sourceDir);
        return base.getResources();
    }


    private Resources createNewResource(Context newBase, String assets) {
        try {
            AssetManager manager = AssetManager.class.newInstance();
            Method method = AssetManager.class.getDeclaredMethod("addAssetPath", String.class);
            method.invoke(manager, assets);
            return new Resources(manager, newBase.getResources().getDisplayMetrics(), newBase.getResources().getConfiguration());
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return null;

    }

    protected int getLBTheme() {
        return android.R.style.Theme;
    }

    public static class LebianContext extends ContextWrapper {

        private Resources resources;
        private Resources.Theme mTheme;
        private int themeId;

        public LebianContext(Context base, int themeResId,Resources resources) {
            super(base);
            this.resources = resources;
            this.themeId = themeResId;
        }

        @Override
        public Context getBaseContext() {
            return super.getBaseContext();
        }

        @Override
        public Resources.Theme getTheme() {
            if (mTheme==null){
                mTheme =  resources.newTheme();
                mTheme.applyStyle(themeId,true);
            }
            return mTheme;

        }


        @Override
        public Resources getResources() {
            return resources;
        }

        @Override
        public AssetManager getAssets() {
            return resources.getAssets();
        }
    }

}
