package com.dongnao.skindavid;

import android.content.Context;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.graphics.drawable.Drawable;
import android.support.v4.content.ContextCompat;

import java.lang.reflect.Method;

/**
 * Created by Administrator on 2018/2/8 0008.
 */

public class SkinManager {
//外置卡
    private Resources skinResource;

    private Resources appResource;

    private Context context;

    private  String skinPackage;

    public void setContext(Context context) {
        this.context = context;
    }

    private static final SkinManager ourInstance = new SkinManager();

    public static SkinManager getInstance() {
        return ourInstance;
    }

    private SkinManager() {

    }

    public  void loadSkin() {
        String path = context.getDir("skin", Context.MODE_PRIVATE).getAbsolutePath()+"/skin.apk";
        AssetManager assetManager = null;
        PackageManager packageManager=context.getPackageManager();
        //拿到外置卡皮肤apk 的包名
        skinPackage=packageManager.getPackageArchiveInfo(path,PackageManager.GET_ACTIVITIES).packageName;

        appResource = context.getResources();
        try {
            assetManager = AssetManager.class.newInstance();
            Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
            addAssetPath.invoke(assetManager, path);
            skinResource = new Resources(assetManager, context.getResources().getDisplayMetrics(), context
                    .getResources().getConfiguration());
        } catch ( Exception e) {
            e.printStackTrace();
        }
    }


    public int getColor(int resId) {
        if (skinResource == null) {
            return resId;
        }
        String resName = appResource.getResourceEntryName(resId);
        int skinId = skinResource.getIdentifier(resName, "color", skinPackage);
        if (skinId == 0) {
            return resId;
        }
        return skinResource.getColor(skinId);
    }

    public Drawable getDrawable(int id) {
        if (skinResource == null) {
            return ContextCompat.getDrawable(context, id);
        }
        String resName = context.getResources().getResourceEntryName(id);
        int skinId=skinResource.getIdentifier(resName, "drawable", skinPackage);

        if (skinId == 0) {
            return ContextCompat.getDrawable(context, id);
        }
        return skinResource.getDrawable(skinId);
    }
}
