package com.reactlibrary.util;

import android.content.Context;
import android.text.TextUtils;

import com.reactlibrary.bean.UpdateBean;
import com.reactlibrary.bundle.CreateFileUtil;
import com.reactlibrary.bundle.DecompressionUtil;
import com.reactlibrary.constant.Constant;
import com.reactlibrary.data.BundleKeepSp;
import com.reactlibrary.download.DownloadListener;
import com.reactlibrary.download.DownloadUtils;
import com.reactlibrary.updatebundle.fullupdata.FullUpdataBundle;

import java.io.File;

/**
 * 提供给Rn使用bundle的下载
 *
 * Created by MJX  on 2018/9/6 14:36.
 */
public class RnBundleUtil {
    private static Context context;
    /**
     * 下载bundle的压缩包
     * @param updateBean
     */
    public static void downLoadBundleZip(final Context contextPar, final UpdateBean updateBean, final IUpdateBundleListener mIUpdateBundleListener){
        if(contextPar == null){
            System.out.println("下载bundle的压缩包");
            return;
        }
        context = contextPar;
        try {
            if(updateBean == null){
                System.out.println("Rn传递的updateBean为空");
                return;
            }

            if(updateBean.getBundleName() == null || TextUtils.isEmpty(updateBean.getBundleName())){
                System.out.println("Rn传递的BundleName为空");
                return;
            }

            if(updateBean.getUrl() == null || TextUtils.isEmpty(updateBean.getUrl())){
                System.out.println("Rn传递的url为空");
                return;
            }

            if(updateBean.getVersionName() == null || TextUtils.isEmpty(updateBean.getVersionName())){
                System.out.println("Rn传递的versionName为空");
                return;
            }

            if(updateBean.getHashCodeStr() == null || TextUtils.isEmpty(updateBean.getHashCodeStr())){
                System.out.println("Rn传递的HashCodeStr为空");
                return;
            }

            if(updateBean.getIsincrement() == null || TextUtils.isEmpty(updateBean.getIsincrement())){
                System.out.println("Rn传递的isincrement为空");
                return;
            }

            if(updateBean.getBundleCode() == null || TextUtils.isEmpty(updateBean.getBundleCode())){
                System.out.println("Rn传递的BundleCode为空");
                return;
            }

            String bundlezip = context.getFilesDir() + "/" + Constant.BUNDLE_ZIP_FILE_NAME + "/" +updateBean.getBundleName() + ".zip";
            final String combinedValue = updateBean.getVersionName() + "-" + updateBean.getBundleName() + "-" + updateBean.getHashCodeStr()+"-"+updateBean.getIsincrement();
            String bundleCode = updateBean.getBundleCode();
            String bundleKeepInfo = BundleKeepSp.getBundleKeepInfo(context);
            if(!combinedValue.equals(bundleKeepInfo)){ //不用断点续传
                //删除文件
                File bundleFile = new File(bundlezip);
                if(bundleFile.exists()){
                    bundleFile.delete();
                }
                bundleFile.createNewFile();
            }
            DownloadUtils.getInstance().startDownload(updateBean.getUrl(),bundlezip);
            DownloadUtils.getInstance().setListener(new DownloadListener() {
                @Override
                public void startDownload() {
                    //记录下载的bundle的信息
                    BundleKeepSp.saveBundleKeepInfo(context,combinedValue);
                }

                @Override
                public void pauseDownload() {

                }

                @Override
                public void finishDownload() {
                    try {
//                        // 文件夹地址
//                        String str = MainApplication.getContext().getFilesDir() + "/" + Constant.BUNDLE_FILE_NAME + "/";
//                        //解压缩包
//                        ZipUtil.unZipFiles(bundlezip, str);
//                        //这里如果是全量包，就加载全量的bundle
//                        //把图片全部移植过去，把字符串全部移植过去
//                        String bundleCodeStr = "";
//                        if (!TextUtils.isEmpty(bundleCode)) {
//                            bundleCodeStr = bundleCode.replace(".", "_");
//                        } else {
//                            return;
//                        }
                        if("0".equals(updateBean.getIsincrement())){  //全量更新
                            updateFullBundle(updateBean,mIUpdateBundleListener);
                        }else if("1".equals(updateBean.getIsincrement())){ //增量更新
                            updateIncrementBundle(updateBean,mIUpdateBundleListener);
                        }

                    } catch (Exception e) {
                        e.printStackTrace();

                    }
                }


                @Override
                public void downloadProgress(final long progress) {
                    System.out.println("起始的下载位置："+progress);
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//
//                        }
//                    });
                }

                @Override
                public void downloadError(String error) {
                    //下载异常的处理

                }
            });

        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Rn下载bundle出现异常");
        }
    }


    public static void updateFullBundle(UpdateBean updateBean,IUpdateBundleListener mIUpdateBundleListener){
        try {
            // 下载成功后需要做的工作
            File file = null;
            //bundle的zip解压后的路径
            CreateFileUtil.setContext(context);
            String bundleStr = CreateFileUtil.getFilePath("bundle", "");
            File path = BundleInfoSp.getLoadBundZipFile(updateBean.getBundleName());
            file = new File(path.getAbsolutePath());
            DecompressionUtil.unZipFile(file, bundleStr);
            String hashCode = updateBean.getHashCodeStr();
            String bundleName = updateBean.getBundleName();
            String bundleCode = updateBean.getBundleCode();
            String fileStr = BundleInfoSp.getBundleValue(context,"fileStr");
            String initBundleFile = BundleInfoSp.getBundleValue(context,"initBundleFile");
            String oldPath = fileStr + "/" + initBundleFile + "/index.android.bundle";
            File filesDir = context.getFilesDir();
            String newPath = filesDir + "/" + "bundle" + "/" + bundleName + "/index.android.bundle";
            FullUpdataBundle.startFullUpdataBundle(context,oldPath, newPath, hashCode, bundleName, bundleCode);
            if(mIUpdateBundleListener != null){
                mIUpdateBundleListener.updateSuccess("0");
                System.out.println("全量更新成功------------");
            }else{
                mIUpdateBundleListener.updateError("0");
                System.out.println("全量更新失败------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("全量更新异常------------");
            if(mIUpdateBundleListener != null){
                mIUpdateBundleListener.updateSuccess("0");
            }else{
                mIUpdateBundleListener.updateError("0");
            }
        }
    }

    public static void updateIncrementBundle(UpdateBean updateBean,IUpdateBundleListener mIUpdateBundleListener ){
        try {
            String bundleStr = CreateFileUtil.getFilePath("bundle", "");
            File path = BundleInfoSp.getLoadBundZipFile(updateBean.getBundleName());
            File file = new File(path.getAbsolutePath());
            DecompressionUtil.unZipFile(file, bundleStr);
            String hashCode = updateBean.getHashCodeStr();
            String bundleName = updateBean.getBundleName();
            String bundleCode = updateBean.getBundleCode();
            String fileStr = BundleInfoSp.getBundleValue(context,"fileStr");
            String initBundleFile = BundleInfoSp.getBundleValue(context,"initBundleFile");
            String oldPath = fileStr + "/" + initBundleFile + "/index.android.bundle";
            File filesDir = context.getFilesDir();
            String newPath = filesDir + "/" + "bundle" + "/" + bundleName + "/index.android.bundle";
            FullUpdataBundle.BundleIncrementalUpdate(context,oldPath, newPath, bundleName, bundleCode, hashCode);
            if(mIUpdateBundleListener != null){
                mIUpdateBundleListener.updateSuccess("1");
                System.out.println("增量更新成功------------");
            }else{
                mIUpdateBundleListener.updateError("1");
                System.out.println("增量更新失败------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("增量更新异常------------");
            if(mIUpdateBundleListener != null){
                mIUpdateBundleListener.updateSuccess("1");
                System.out.println("增量更新成功------------");
            }else{
                mIUpdateBundleListener.updateError("1");
                System.out.println("增量更新失败------------");
            }
        }
    }


    public interface IUpdateBundleListener{
        void updateSuccess(String tag);
        void updateError(String tag);
    }
}
