package com.mogo.skin;

import android.app.Activity;
import android.app.Application;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.text.TextUtils;
import android.util.Log;

import com.mogo.skin.net.DownloadManager;
import com.mogo.skin.utils.FileUtils;
import com.mogo.skin.utils.SkinPreference;
import com.mogo.skin.utils.SkinResources;

import java.io.File;
import java.lang.reflect.Method;
import java.util.Observable;

/**
 * donghongyu
 */
public class SkinManager extends Observable {

    private static String TAG = "SkinManager";

    private static Application mApplication;
    private static SkinManager instance;
    private SkinActivityLifecycle skinActivityLifecycle;
    private Application application;

    public static void init(Application application) {
        synchronized (SkinManager.class) {
            if (null == instance) {
                mApplication = application;
                instance = new SkinManager(application);
            }
        }
    }

    public static SkinManager getInstance() {
        return instance;
    }

    private SkinManager(Application application) {
        this.application = application;
        SkinPreference.init(application);
        SkinResources.init(application);
        //注册Activity生命周期回调
        skinActivityLifecycle = new SkinActivityLifecycle();
        application.registerActivityLifecycleCallbacks(skinActivityLifecycle);
        loadSkin(SkinPreference.getInstance().getSkin());
    }

    /**
     * 加载皮肤包 并 更新
     *
     * @param path 皮肤包路径
     */
    public void loadSkin(String path) {
        Log.d(TAG, "加载皮肤路径：" + path);
        //还原默认皮肤包
        if (TextUtils.isEmpty(path)) {
            SkinPreference.getInstance().setSkin("");
            SkinResources.getInstance().reset();
        }
        // 加载指定目录下的皮肤
        else {
            try {
                AssetManager assetManager = AssetManager.class.newInstance();
                // 添加资源进入资源管理器
                Method addAssetPath = assetManager.getClass().getMethod("addAssetPath", String.class);
                addAssetPath.setAccessible(true);
                addAssetPath.invoke(assetManager, path);

                Resources resources = application.getResources();
                // 横竖、语言
                Resources skinResource = new Resources(assetManager, resources.getDisplayMetrics(), resources.getConfiguration());
                //获取外部Apk(皮肤包) 包名
                PackageManager mPm = application.getPackageManager();
                PackageInfo info = mPm.getPackageArchiveInfo(path, PackageManager.GET_ACTIVITIES);
                String packageName = info.packageName;
                SkinResources.getInstance().applySkin(skinResource, packageName);
                //保存当前使用的皮肤包
                SkinPreference.getInstance().setSkin(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //应用皮肤包
        setChanged();
        //通知观察者
        notifyObservers();
    }

    public void updateSkin(Activity activity) {
        skinActivityLifecycle.updateSkin(activity);
    }


    /**
     * 下载皮肤包
     */
    public void selectSkin(Context context, Skin skin) {
        File theme = new File(FileUtils.getExternalAppDirectory(context), "theme");
        if (theme.exists() && theme.isFile()) {
            theme.delete();
        }
        theme.mkdirs();
        File skinFile = skin.getSkinFile(theme);
        if (skinFile.exists()) {
            Log.e("SkinActivity", "皮肤已存在,开始换肤……");
            SkinManager.getInstance().loadSkin(skin.path);
            return;
        }
        Log.e("SkinActivity", "皮肤不存在,开始下载……");
        DownloadManager manager = getDownloadManager(skin, theme);
        manager.startDownload();

    }

    private static DownloadManager getDownloadManager(Skin skin, File theme) {
        DownloadManager.DownloadListener downloadListener = new DownloadManager.DownloadListener() {
            @Override
            public void onProgressUpdate(int progress) {
                // 更新UI或日志
                Log.d("DownloadManager", "onProgressUpdate progress = " + progress);

            }

            @Override
            public void onDownloadSuccess() {
                // 下载成功后的处理
                Log.d("DownloadManager", "onDownloadSuccess");
                File skinFile = skin.getSkinFile(theme);
                try {
                    //下载成功，将皮肤包信息insert已下载数据库
                    Log.e("SkinActivity", "皮肤包下载完成开始校验");
                    //皮肤包的md5校验 防止下载文件损坏(但是会减慢速度。从数据库查询已下载皮肤表数据库中保留md5字段)
                    if (TextUtils.equals(SkinUtils.getSkinMD5(skinFile), skin.md5)) {
                        Log.d("SkinActivity", "校验成功,修改文件名。");

                    } else {
                        Log.e("SkinActivity", "校验出错,本地文件MD5 与云端文件MD5 不一致。");

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                SkinManager.getInstance().loadSkin(skin.path);
            }

            @Override
            public void onDownloadFailed(Exception e) {
                // 下载失败后的处理
                Log.e("DownloadManager", "onDownloadFailed");
                e.printStackTrace();

            }

            @Override
            public void onAlreadyDownloading(String url) {
                // 处理重复下载的情况
                Log.w("DownloadManager", "onAlreadyDownloading url=" + url);

            }
        };

        return new DownloadManager(skin.url, theme, downloadListener);
    }
}
