package basic.update;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

import com.wasu.cs.widget.WAlertDialog;
import com.wasu.module.log.WLog;
import com.wasu.util.ShellUtils;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.util.HashMap;
import java.util.Map;

import basic.app.TvAppLike;
import basic.update.model.UpdateInfo;
import cn.com.wasu.main.R;

/**
 * Created by fanwang on 9/13/16.
 * this util is only used for update api
 */
public class UpdateUtil {

    private static final String TAG = "UpdateUtil";

    /**
     * 组装post数据
     *
     * @return
     */
    public static String composeRequestBody(Context context, String mPlatformInfo) {
        String xml = "";
        try {
            xml = "<?xml version='1.0' encoding='utf-8'?>" +
                    "<request key='CheckUpdate'>" +
                    "<header>" +
                    "<plat>" + mPlatformInfo + "</plat>" +
                    "<format>xml</format>" +
                    "<useragent></useragent>" +
                    "<client-version>" + context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName + "</client-version>" +
                    "</header>" +
                    "<body />" +
                    "</request>";
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return xml;
    }

    /**
     * 读取返回数据
     *
     * @param repString
     * @return
     */
    public static Map<String, String> parseResponse(String repString) {
        ByteArrayInputStream is = new ByteArrayInputStream(repString.getBytes());
        Map<String, String> result = new HashMap<String, String>();
        try {
            XmlPullParserFactory factory = XmlPullParserFactory.newInstance();
            factory.setNamespaceAware(true);
            XmlPullParser parser = factory.newPullParser();
            parser.setInput(is, "UTF-8");
            int eventType = parser.getEventType();
            while (eventType != XmlPullParser.END_DOCUMENT) {
                switch (eventType) {
                    case XmlPullParser.START_DOCUMENT:
                        break;
                    case XmlPullParser.START_TAG:
                        String name = parser.getName();
                        if (name.equalsIgnoreCase(UpdateInfo.NEEDUPDATE)) {
                            result.put(UpdateInfo.NEEDUPDATE, parser.nextText());
                        } else if (name.equalsIgnoreCase(UpdateInfo.UPDATEVERSION)) {
                            result.put(UpdateInfo.UPDATEVERSION, parser.nextText());
                        } else if (name.equalsIgnoreCase(UpdateInfo.UPDATEINFO)) {
                            result.put(UpdateInfo.UPDATEINFO, parser.nextText());
                        } else if (name.equalsIgnoreCase(UpdateInfo.UPDATEURL)) {
                            result.put(UpdateInfo.UPDATEURL, parser.nextText());
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        break;
                }
                eventType = parser.next();
            }
            if (is != null) {
                is.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void wasuShowForceUpdateUI() {
        showUpdateDialog(false);
    }

    public static void wasuShowNotifyUpdateUI() {
        showUpdateDialog(true);
    }

    public static void wasuShowApkUpdatSuccessUI() {
        Toast.makeText(TvAppLike.getContext(), "升级完成", Toast.LENGTH_LONG).show();
    }

    public static void wasuShowApkUpdateFailedUI() {
        Toast.makeText(TvAppLike.getContext(), "此次升级失败，请稍后再尝试", Toast.LENGTH_LONG).show();
    }


    private static WAlertDialog dialog = null;

    /**
     * @param cancelable 是否可以取消对话框
     */
    private static void showUpdateDialog(boolean cancelable) {
        WLog.i(TAG, "showUpdateDialog");
        if (dialog == null) {
            //show a choice dialog,when user choice ok,we do download apk
            dialog = new WAlertDialog(TvAppLike.getContext(), R.style.update_dialog);

            dialog.setTitle("发现新版本,是否升级?");
            dialog.setMessage(ApkPathManager.getsInstance().getServerMsg());
            dialog.setPositiveButton("确定", new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    //new apk file downloaded successfullyT
                    File tmpFile = new File(ApkPathManager.getsInstance().getSavePath(),
                            ApkPathManager.getsInstance().getSaveName());
                    // 加上.apk后缀名
                    ShellUtils.execCommand("mv " + tmpFile.getAbsolutePath() + " " + tmpFile.getAbsolutePath() + ".apk", false, true);
                    final File apkfile = new File(ApkPathManager.getsInstance().getSavePath(), ApkPathManager.getsInstance().getSaveName() + ".apk");
                    if (!apkfile.exists()) {
                        return;
                    }
                    //将文件权限改为666
                    ShellUtils.CommandResult shellRet = ShellUtils.execCommand("chmod 666 " + apkfile.getAbsolutePath(), false, true);

                    //install apk
                    Uri uri = Uri.fromFile(apkfile);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setDataAndType(uri, "application/vnd.android.package-archive");
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    TvAppLike.getContext().startActivity(intent);

                    // when install apk，结束应用，防止用户点击安装后又取消安装
                    android.os.Process.killProcess(android.os.Process.myPid());

                }
            });
            dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
        }

        dialog.setCancelable(cancelable);

        if (!dialog.isShowing()) {
            dialog.show();
        }

    }

}
