package org.SHS.Pult;

import java.io.File;
import android.util.Log;
import android.os.Build;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import org.SHS.Pult.AddressDialog;
import org.SHS.Pult.Bridge;

public class MainActivity extends org.qtproject.qt5.android.bindings.QtActivity {

	public static MainActivity m_instance;

	public MainActivity() {
		m_instance = this;
	}

	@Override
	public void onCreate(Bundle b) {
		super.onCreate(b);
		//getAddress();
		//installAPK("");
	}

	public void installAPK(String path) {

		Context ctx = getApplicationContext();
		File apkPath = new File(ctx.getFilesDir(), "SHS/packages/Pult");
		File apkFile = new File(apkPath, path);

		Uri mainUri;
		Intent intent = new Intent();
		if (Build.VERSION.SDK_INT >= 24) {
			mainUri = FileProvider.getUriForFile(ctx, "org.SHS.Pult.fileprovider", apkFile);
			intent.setAction(android.content.Intent.ACTION_INSTALL_PACKAGE);
			intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
			intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		} else {
			mainUri = Uri.parse("file://" + apkFile.toString());
			intent.setAction(android.content.Intent.ACTION_VIEW);
			intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		}
		//Uri mainUri = Uri.parse("content://org.SHS.Pult.fileprovider/apk_files/" + path);
		//Uri fileUri = Uri.parse("file://" + path);

		//intent.setAction(android.content.Intent.ACTION_VIEW);
		intent.setData(mainUri);
		//intent.setFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
		//intent.putExtra(android.content.Intent.EXTRA_ALLOW_REPLACE, true);
		//intent.putExtra(android.content.Intent.EXTRA_INSTALLER_PACKAGE_NAME, mainUri.toString());
		//Log.d("shs", "install ..." + intent);
		startActivity(intent);
		//Log.d("shs", "install executed");
		//ctx.getPackageManager().installPackage(mainUri, null, 0, "SHS Installer");


	}

	public static void execPackage(String path) {
		m_instance.installAPK(path);
	}

	public static void queryIntent() {
		String uri = new String();
		Intent intent = m_instance.getIntent();
		if (intent != null)
			if (intent.getData() != null)
				uri = intent.getData().toString();
		Bridge.activityStarted(uri);
	}

	public void getAddress(String addr) {
		AddressDialog dialog = new AddressDialog(this, addr);
		dialog.show();
	}

	public static void execDialog(String addr) {
		m_instance.getAddress(addr);
	}

}
