package com.sheep.gamegroup.model.entity;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.text.TextUtils;

import com.kfzs.duanduan.utils.ApkUtils;
import com.sheep.gamegroup.util.Md5Util;
import com.sheep.jiuyan.samllsheep.utils.PackageUtil;

import java.io.File;

import rx.functions.Action1;

/**
 * Created by realicing on 2018/11/9.
 * realicing@sina.com
 * 根据安装包获取相关信息，以下方法顺序执行，否则可能会报各种空指针
 */
public class ApkFileInfo {
    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    private File file;
    public boolean existsPath() {
        file = new File(path);
        return file.exists();
    }

    private String packageName;
    public ApkFileInfo initPackageNameFromPath(Context context) {
        packageName = ApkUtils.getUnInstallApkPackageName(context, path);
        return this;
    }

    public String getPackageName() {
        return packageName;
    }

    private boolean isAppInstalled;
    public boolean checkInstall(Context context) {
        isAppInstalled = PackageUtil.isAppInstalled(context, packageName);
        return isAppInstalled;
    }

    public boolean isAppInstalled() {
        return isAppInstalled;
    }
    //是否 文件与安装的应用是否m签名d5相同
    private boolean isEqualsSignMd5;

    public boolean isEqualsSignMd5() {
        return isEqualsSignMd5;
    }

    private PackageInfo appPackageInfo;
    private PackageInfo filePackageInfo;
    //检查文件与安装的应用是否m签名d5相同
    public boolean checkApkAndFileSignMd5() {
        String appSignMd5 = ApkUtils.getApkSignMd5StrByPackageName(packageName, new Action1<PackageInfo>() {
            @Override
            public void call(PackageInfo packageInfo) {
                appPackageInfo = packageInfo;
            }
        });

        String fileSignMd5 = ApkUtils.getApkSignMd5StrByPath(path, new Action1<PackageInfo>() {
            @Override
            public void call(PackageInfo packageInfo) {
                filePackageInfo = packageInfo;
            }
        });
        isEqualsSignMd5 = TextUtils.equals(fileSignMd5, appSignMd5);
        return isEqualsSignMd5;
    }
    //检查文件与安装的应用是否md5相同
    public boolean checkApkAndFileMd5() {
        return Md5Util.checkMD5(new File(appPackageInfo.applicationInfo.sourceDir), file);
    }

    //根据版本号判断是否可安装成功
    public boolean isCanInstallVersion() {
        return appPackageInfo.versionCode <= filePackageInfo.versionCode;
    }
}
