package com.sheep.gamegroup.view.activity;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.sheep.gamegroup.absBase.BaseActivity;
import com.sheep.gamegroup.model.entity.ApkInfo;
import com.sheep.gamegroup.model.entity.AppInfo;
import com.sheep.gamegroup.util.ListUtil;
import com.sheep.gamegroup.util.StringUtils;
import com.sheep.gamegroup.util.SysAppUtil;
import com.sheep.gamegroup.util.ViewHolder;
import com.sheep.gamegroup.util.ViewUtil;
import com.sheep.gamegroup.util.ZipChannelUtil;
import com.sheep.gamegroup.view.adapter.AdbCommonRecycler;
import com.sheep.jiuyan.samllsheep.R;
import com.sheep.jiuyan.samllsheep.SheepApp;
import com.sheep.jiuyan.samllsheep.utils.G;
import com.sheep.jiuyan.samllsheep.utils.TitleBarUtils;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;

import static com.sheep.jiuyan.samllsheep.utils.ClassFileHelper.DIR;

/**
 * Created by realicing on 2018/6/19.
 * realicing@sina.com
 */
public class ActSheepApkList extends BaseActivity {
    @Override
    protected int getLayoutId() {
        return R.layout.act_user_label_list;
    }


    @BindView(R.id.user_label_list)
    RecyclerView user_label_list;

    @BindView(R.id.user_label_commit_tv)
    TextView user_label_commit_tv;

    @Override
    public void initView() {
        TitleBarUtils
                .getInstance()
                .setTitle(this, "Sheep目录Apk渠道测试")
                .setTitleFinish(this);
        user_label_commit_tv.setVisibility(View.GONE);
    }

    @Override
    public void initListener() {

    }

    @Override
    public void initData() {
        loadData(getList());
    }

    private List<ApkInfo> getList() {
        List<ApkInfo> apkInfoList = ListUtil.emptyList();

        File dir = new File(DIR);
        File[] files = dir.listFiles();
        if(files != null)
            for (File file : files) {
                apkInfoList.add(getAppInfo(getApplicationContext(), file));
            }
        return apkInfoList;
    }
    public static boolean onlyZip = true;
    public static ApkInfo getAppInfo(Context context, File file) {
        ApkInfo apkInfo = new ApkInfo();
        PackageManager packageManager = context.getPackageManager();
        String absolutePath = file.getAbsolutePath();
        AppInfo appInfo = new AppInfo();
        if(!onlyZip){
            PackageInfo pkgInfo = getPackageInfo(context, absolutePath);
            if (pkgInfo == null) {
                return apkInfo;
            }
            pkgInfo.applicationInfo.sourceDir = absolutePath;
            pkgInfo.applicationInfo.publicSourceDir = absolutePath;

            //程序包名
            String packageName = pkgInfo.packageName;
            appInfo.setPackageName(packageName);
            //获取到图标
            Drawable icon = pkgInfo.applicationInfo.loadIcon(packageManager);
            appInfo.setIcon(icon);
            //获取到应用的名字
            String appName = pkgInfo.applicationInfo.loadLabel(packageManager).toString();
            appInfo.setAppName(appName);
            appInfo.setSha1(SysAppUtil.getSHA1(pkgInfo));

        }
        //获取到安装包的路径
        appInfo.setSourceDir(absolutePath);
        //获取到安装apk的大小
        long apkSize = file.length();
        //格式化apk的大小
        appInfo.setApkSize(Formatter.formatFileSize(SheepApp.getInstance(), apkSize));
        apkInfo.setAppInfo(appInfo);
        apkInfo.setFile(file);
        try {
            String comment = ZipChannelUtil.readQUA(apkInfo.getFile());
            apkInfo.setComment(comment);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return apkInfo;
    }
    //得到PackageInfo对象
    public static PackageInfo getPackageInfo(Context context, String apkFilepath) {
        PackageManager pm = context.getPackageManager();
        PackageInfo pkgInfo = null;
        try {
            pkgInfo = pm.getPackageArchiveInfo(apkFilepath, PackageManager.GET_ACTIVITIES | PackageManager.GET_SIGNATURES);
        } catch (Exception e) {
            // should be something wrong with parse
            e.printStackTrace();
        }
        return pkgInfo;
    }
    private void loadData(List<ApkInfo> list) {
        user_label_list.setLayoutManager(new LinearLayoutManager(SheepApp.getInstance()));
        user_label_list.setAdapter(new AdbCommonRecycler<ApkInfo>(SheepApp.getInstance(), list){

            @Override
            public int getViewIdByType(int type) {
                return R.layout.app_info_item;
            }

            @Override
            public void convert(ViewHolder holder, final ApkInfo item) {
                ImageView app_info_iv = holder.itemView.findViewById(R.id.app_info_iv);
                TextView app_info_name_tv = holder.itemView.findViewById(R.id.app_info_name_tv);
                TextView app_info_package_name_tv = holder.itemView.findViewById(R.id.app_info_package_name_tv);
                TextView app_info_size_tv = holder.itemView.findViewById(R.id.app_info_size_tv);
                TextView app_info_path_tv = holder.itemView.findViewById(R.id.app_info_path_tv);

                final AppInfo appInfo = item.getAppInfo();
                if(appInfo == null){
                    return;
                }
                if(appInfo.getIcon() != null)
                    app_info_iv.setImageDrawable(appInfo.getIcon());
                ViewUtil.setText(app_info_name_tv, appInfo.getAppName());
                app_info_name_tv.append(item.getComment());//CommonUtil.getFileMD5(item.getFile())
                ViewUtil.setText(app_info_package_name_tv, appInfo.getPackageName());
                ViewUtil.setText(app_info_size_tv, appInfo.getApkSize());
                ViewUtil.setText(app_info_path_tv, appInfo.getSourceDir()+"\n"+appInfo.getSha1());

                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        try {
                            onClickItem(item);
                        } catch (IOException e) {
                            e.printStackTrace();
                            G.showToast(e.getMessage());
                        }
                    }
                });
                holder.itemView.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {
                        StringUtils.CopyText(appInfo.getSha1());
                        G.showToast("复制sha1成功："+appInfo.getSha1());
                        return true;
                    }
                });
            }
        });

    }

    private void onClickItem(final ApkInfo apkInfo) throws IOException {
        if(TextUtils.isEmpty(apkInfo.getComment())){
            String comment = "976873";
            ZipChannelUtil.writeQUA(apkInfo.getFile(), comment);
            apkInfo.setComment(comment);
            user_label_list.getAdapter().notifyDataSetChanged();
            G.showToast("给apk添加zip注释作为渠道成功");
        } else {
            ZipChannelUtil.delQUA(apkInfo.getFile());
            G.showToast("成功删除渠道："+apkInfo.getComment());
            apkInfo.setComment("");
            user_label_list.getAdapter().notifyDataSetChanged();
        }
    }

    @OnClick({R.id.user_label_commit_tv})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.user_label_commit_tv:
                toCommit();
                break;
        }
    }

    private void toCommit() {
    }

}
