package com.kfzs.duanduan.db;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.text.TextUtils;

import com.sheep.jiuyan.samllsheep.BuildConfig;
import com.kfzs.duanduan.KFZSApp;
import com.kfzs.duanduan.data.graph.provider.channel.Channel;
import com.kfzs.duanduan.datashare.DDProviderHelper;
import com.kfzs.duanduan.utils.ApkUtils;
import com.kfzs.duanduan.utils.sys.ChannelContent;

/**
 * <pre>
 *     sinlov
 *
 *     /\__/\
 *    /`    '\
 *  ≈≈≈ 0  0 ≈≈≈ Hello world!
 *    \  --  /
 *   /        \
 *  /          \
 * |            |
 *  \  ||  ||  /
 *   \_oo__oo_/≡≡≡≡≡≡≡≡o
 *
 * </pre>
 * Created by sinlov on 17/3/6.
 */
public class DataSave {
    private static DataSave instance;
    private String apkSign;
    private String channelName;
    private String umengKey;
    private Bundle appMetaData;
    private String extrasFromGame;

    public String getExtrasFromGame() {
        return extrasFromGame;
    }

    public void setExtrasFromGame(String extrasFromGame) {
        this.extrasFromGame = extrasFromGame;
    }

    public String getApkSign() {
        if (apkSign == null) {
            apkSign = ApkUtils.getApkSignatureByPackageName(KFZSApp.getInstance(), KFZSApp.getInstance().getPackageName());
        }
        return apkSign;
    }

    public Bundle getAppMetaData() throws PackageManager.NameNotFoundException {
        if (appMetaData == null) {
            ApplicationInfo appInfo = KFZSApp.context.getPackageManager().getApplicationInfo(
                    KFZSApp.context.getPackageName(), PackageManager.GET_META_DATA);
            appMetaData = appInfo.metaData;
        }
        return appMetaData;
    }

    public String getChannelName() {
        if (channelName == null) {
            boolean hasChannel = ChannelContent.getInstance().initChannelContent(KFZSApp.context);
            if (hasChannel) {
                channelName = ChannelContent.getInstance().getChannel_name();
            } else {
                try {
                    channelName = getAppMetaData().getString("UMENG_CHANNEL");
                    DDProviderHelper.getInstance().setChannel(KFZSApp.context,new Channel(1L,channelName,null));
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
        return channelName;
    }

    public String getUmengKey() {
        if (umengKey == null) {
            if (TextUtils.isEmpty(BuildConfig.umeng_appkey)) {
                umengKey = BuildConfig.umeng_appkey;
            } else {
                umengKey = "58bd0a3475ca3518a2002436";
            }
        }
        return umengKey;
    }

    public static synchronized DataSave getInstance() {
        if (instance == null) {
            instance = new DataSave();
        }
        return instance;
    }

    private DataSave() {
    }
}
