package com.danding.yang800.Util;

import android.content.ComponentName;
import android.content.ServiceConnection;
import android.os.Environment;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.danding.yang800.BaseActivity;
import com.danding.yang800.LoginActivity;
import com.danding.yang800.R;
import com.danding.yang800.Update.AppUpdateUtils;
import com.danding.yang800.Update.DownloadService;
import com.danding.yang800.Update.NumberProgressBar;
import com.danding.yang800.Update.OkGoUpdateHttpUtil;
import com.danding.yang800.Update.UpdateAppBean;
import com.danding.yang800.Update.UpdateAppManager;
import com.danding.yang800.Update.UpdateCallback;

import java.io.File;

/**
 * Created by Administrator on 2018/1/9.
 */
public class UpdateUtil {
    UpdateAppBean updateApp;
    BaseActivity context;
    boolean mustUpdate = false;
    private PopupWindow popupWindow;

    public UpdateUtil(BaseActivity context) {
        this.context = context;
    }

    public void updateDiy(final boolean permisson) {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();
        AppUpdateUtils.deleteFolderFile(path + File.separator + "app");
        new UpdateAppManager
                .Builder()
                .setActivity(context)
                .setHttpManager(new OkGoUpdateHttpUtil())
                .setUpdateUrl("appApk.getUpdateInfo")
                .setPost(false)
                .setTargetPath(path)
                .build()
                .checkNewApp(new UpdateCallback() {
                    @Override
                    protected UpdateAppBean parseJson(UpdateAppBean updateAppBean) {
                        return updateAppBean;
                    }

                    @Override
                    public void hasNewApp(UpdateAppBean update, UpdateAppManager updateAppManager, String update_log, String update_must) {
                        updateApp = update;
                        showWindow(update_log, update_must, context, permisson);
                    }

                    /**
                     * 网络请求之前
                     */
                    @Override
                    public void onBefore() {
                    }

                    /**
                     * 网路请求之后
                     */
                    @Override
                    public void onAfter() {
                    }

                    /**
                     * 没有新版本
                     */
                    @Override
                    public void noNewApp() {
                    }

                });
    }

    NumberProgressBar progressBar;
    Button btn_ok;

    public void showWindow(String update_log, final String update_must, final BaseActivity context, final boolean permisson) {
        if (update_must.equals("1")) {
            mustUpdate = true;
            //TODO application赋值mustUpdate，所需类取
        }
        View contentView = LayoutInflater.from(context).inflate(
                R.layout.lib_update_app_dialog, null);
        popupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT, true);
        btn_ok = (Button) contentView.findViewById(R.id.btn_ok);
        progressBar = (NumberProgressBar) contentView.findViewById(R.id.progressBar);
        TextView tv_update_info = (TextView) contentView.findViewById(R.id.tv_update_info);
        tv_update_info.setText(update_log);
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (permisson) {
                    if (update_must.equals("0")) {
//                        updateAppManager.download();
                        popupWindow.dismiss();
                        mustUpdate = false;
                        DownloadService.bindService(context, conn);
                    } else {
                        mustUpdate = true;
                        btn_ok.setVisibility(View.GONE);
                        progressBar.setVisibility(View.VISIBLE);
                        DownloadService.bindService(context, conn);
                    }
                } else {
                    Toast.makeText(context, "没有读取存储权限", Toast.LENGTH_SHORT).show();
                }

            }

        });
        ImageView iv_close = (ImageView) contentView.findViewById(R.id.iv_close);
        iv_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (update_must.equals("0")) {
                    popupWindow.dismiss();
                } else {
                    context.finish();
                }

            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.showAtLocation(contentView, Gravity.BOTTOM, 0, 0);
    }

    private ServiceConnection conn = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            startDownloadApp((DownloadService.DownloadBinder) service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };

    private void startDownloadApp(DownloadService.DownloadBinder binder) {
        // 开始下载，监听下载进度，可以用对话框显示
        if (updateApp != null) {

            binder.start(updateApp, new DownloadService.DownloadCallback() {
                @Override
                public void onStart() {
                    progressBar.setVisibility(View.VISIBLE);
                }

                @Override
                public void onProgress(float progress, long totalSize) {
                    if (mustUpdate) {
                        progressBar.setProgress(Math.round(progress * 100));
                        progressBar.setMax(100);
                    }
                }

                @Override
                public void setMax(long total) {

                }

                @Override
                public boolean onFinish(File file) {
                    if (mustUpdate)
                        popupWindow.dismiss();
                    return true;
                }

                @Override
                public void onError(String msg) {
                    if (mustUpdate)
                        popupWindow.dismiss();
                }
            });
        }
    }

}
