package com.vsu.fcounter.installer;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;

import androidx.core.content.FileProvider;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

class InstallerModule extends ReactContextBaseJavaModule {

    private ReactContext reactContext;

    @Override
    public String getName() {
        return "Installer";
    }

    InstallerModule(ReactApplicationContext reactContext) {
        super(reactContext);
        this.reactContext = reactContext;
    }

    @ReactMethod
    private void download(String httpUrl, String fileName, Promise promise) {
        String path = Environment.getExternalStorageDirectory().getPath() + "/" + fileName;
        final File file = new File(path);
        try {
            URL url = new URL(httpUrl);
            try {
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                InputStream is = conn.getInputStream();
                FileOutputStream fos = new FileOutputStream(file);
                byte[] buf = new byte[256];
                conn.connect();
                if (conn.getResponseCode() >= 400) {
                    promise.resolve(false);
                    return;
                } else {
                    while (true) {
                        if (is != null) {
                            int numRead = is.read(buf);
                            if (numRead <= 0) break;
                            else fos.write(buf, 0, numRead);
                        } else break;
                    }
                }
                conn.disconnect();
                fos.close();
                if (is != null) is.close();
            } catch (IOException e) {
                e.printStackTrace();
                promise.resolve(false);
                return;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            promise.resolve(false);
            return;
        }
        promise.resolve(path);
    }

    /**
     * 普通调起安装器方式
     * @param filePath 安装包apk路径
     */
    @ReactMethod
    private void install(String filePath) {
        File file = new File(filePath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        Uri data;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//判断版本大于等于7.0
            // "sven.com.fileprovider.fileprovider"即是在清单文件中配置的authorities
            // 通过FileProvider创建一个content类型的Uri
            data = FileProvider.getUriForFile(reactContext, "com.vsu.fcounter.fileprovider", file);
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);// 给目标应用一个临时授权
        } else {
            data = Uri.fromFile(file);
        }
        intent.setDataAndType(data, "application/vnd.android.package-archive");
        reactContext.startActivity(intent);
    }

    /**
     * 广播方式安装应用
     * @param filePath 安装包apk路径
     */
    @ReactMethod
    private void installApp(String filePath) {
        Intent intent = new Intent("android.intent.action.UNION_SILIENT_INSTALL");
        intent.setPackage("com.android.systemui");
        intent.putExtra("file_path", filePath);
        intent.putExtra("send_package_name", this.reactContext.getPackageName());
        intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
        this.reactContext.sendBroadcast(intent);
    }

    @ReactMethod
    private void uninstall(String packageName) {
        Uri packageURI = Uri.parse("package:"+packageName);
        Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);
        reactContext.startActivity(uninstallIntent);
    }

}
