package com.ubugtrack;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Build;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * www.ubugtrack.com - Crash Reporter for Android, version 2
 * Sends the uncaught exceptions of an app (Java or Kotlin, Android 5.0+) to the
 * Crash Reporter of a uBugtrack project.
 *
 * In Application.onCreate():
 *     CrashReporter.init("YOUR_CRASH_KEY", this);
 *
 * AndroidManifest.xml needs: <uses-permission android:name="android.permission.INTERNET" />
 *
 * The crash is saved first, then sent: a crash that could not be sent (no network)
 * is sent at the next launch. Then the app ends as usual: Android's crash dialog,
 * Play Console vitals and the other crash reporters still see the crash.
 */
public final class CrashReporter implements Thread.UncaughtExceptionHandler
{
	private static final String ENDPOINT = "https://ubugtrack.com/crashdump.php";
	private static final int TIMEOUT_MS = 4000;
	private static final String PENDING_FOLDER = "ubugtrack_crashes";
	private static final int MAX_PENDING = 5;

	private static boolean installed = false;

	private final String projectKey;
	private final String endpoint;
	private final String appVersion;
	private final File pendingFolder;
	private final Thread.UncaughtExceptionHandler previous;

	/**
	 * Call it once, in Application.onCreate().
	 */
	public static void init(String projectKey, Context context)
	{
		init(projectKey, context, ENDPOINT);
	}

	/**
	 * endpoint: only to send to another uBugtrack server (tests).
	 */
	public static synchronized void init(String projectKey, Context context, String endpoint)
	{
		if (installed)
			return;
		installed = true;

		Context application = context.getApplicationContext() != null ? context.getApplicationContext() : context;
		CrashReporter reporter = new CrashReporter(projectKey, application, endpoint, Thread.getDefaultUncaughtExceptionHandler());
		Thread.setDefaultUncaughtExceptionHandler(reporter);
		reporter.sendPendingLater();
	}

	private CrashReporter(String projectKey, Context context, String endpoint, Thread.UncaughtExceptionHandler previous)
	{
		this.projectKey = projectKey;
		this.endpoint = endpoint;
		this.appVersion = versionName(context);
		this.pendingFolder = new File(context.getNoBackupFilesDir(), PENDING_FOLDER);
		this.previous = previous;
	}

	@Override
	public void uncaughtException(Thread thread, Throwable error)
	{
		try
		{
			final String body = formBody(error);
			final File saved = save(body);

			// No network on the main thread: another thread sends it, a few seconds at most
			Thread sender = new Thread(() ->
			{
				if (post(body) && saved != null)
					delete(saved);
			}, "ubugtrack-crash");
			sender.start();
			sender.join(TIMEOUT_MS + 1000);
		}
		catch (Throwable ignored)
		{
			// The crash reporter must never hide the crash
		}
		finally
		{
			if (previous != null)
				previous.uncaughtException(thread, error);
			else
				System.exit(1);
		}
	}

	//*********************************************************************
	// Report

	private String formBody(Throwable error) throws Exception
	{
		StringWriter trace = new StringWriter();
		error.printStackTrace(new PrintWriter(trace));

		Map<String, String> fields = new LinkedHashMap<>();
		fields.put("project_key", projectKey);
		fields.put("logtitle", String.valueOf(error));
		fields.put("logfull", trace.toString());
		fields.put("device", Build.DEVICE);
		fields.put("manufacturer", Build.MANUFACTURER);
		fields.put("model", Build.MODEL);
		fields.put("fingerprint", Build.FINGERPRINT);
		fields.put("appversion", appVersion);

		StringBuilder body = new StringBuilder();
		for (Map.Entry<String, String> field : fields.entrySet())
		{
			if (body.length() > 0)
				body.append('&');
			body.append(URLEncoder.encode(field.getKey(), "UTF-8")).append('=');
			body.append(URLEncoder.encode(field.getValue() != null ? field.getValue() : "", "UTF-8"));
		}
		return body.toString();
	}

	@SuppressWarnings("deprecation")
	private static String versionName(Context context)
	{
		try
		{
			PackageManager manager = context.getPackageManager();
			// getPackageInfo(String, int) is deprecated since Android 13 (API 33)
			PackageInfo info = Build.VERSION.SDK_INT >= 33
				? manager.getPackageInfo(context.getPackageName(), PackageManager.PackageInfoFlags.of(0))
				: manager.getPackageInfo(context.getPackageName(), 0);
			// The server ignores a report without version
			return info.versionName != null && !info.versionName.isEmpty() ? info.versionName : "unknown";
		}
		catch (Exception ignored)
		{
			return "unknown";
		}
	}

	private boolean post(String body)
	{
		HttpURLConnection connection = null;
		try
		{
			byte[] bytes = body.getBytes(StandardCharsets.UTF_8);
			connection = (HttpURLConnection) URI.create(endpoint).toURL().openConnection();
			connection.setConnectTimeout(TIMEOUT_MS);
			connection.setReadTimeout(TIMEOUT_MS);
			connection.setRequestMethod("POST");
			connection.setDoOutput(true);
			connection.setFixedLengthStreamingMode(bytes.length);
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
			try (OutputStream output = connection.getOutputStream())
			{
				output.write(bytes);
			}
			int code = connection.getResponseCode();
			return code >= 200 && code < 300;
		}
		catch (Exception ignored)
		{
			return false;
		}
		finally
		{
			if (connection != null)
				connection.disconnect();
		}
	}

	//*********************************************************************
	// Crashes not sent yet, kept in the app files (not backed up)

	private File save(String body)
	{
		try
		{
			if (!pendingFolder.isDirectory() && !pendingFolder.mkdirs())
				return null;

			// Only the last ones
			File[] files = pendingFolder.listFiles();
			if (files != null && files.length >= MAX_PENDING)
			{
				Arrays.sort(files);
				for (int i = 0; i <= files.length - MAX_PENDING; i++)
					delete(files[i]);
			}

			File file = new File(pendingFolder, System.currentTimeMillis() + ".crash");
			try (OutputStream output = new FileOutputStream(file))
			{
				output.write(body.getBytes(StandardCharsets.UTF_8));
			}
			return file;
		}
		catch (Exception ignored)
		{
			return null;
		}
	}

	private void sendPendingLater()
	{
		Thread thread = new Thread(() ->
		{
			File[] files = pendingFolder.listFiles();
			if (files == null)
				return;
			for (File file : files)
			{
				String body = read(file);
				if (body == null || post(body))
					delete(file);
			}
		}, "ubugtrack-pending");
		thread.setDaemon(true);
		thread.start();
	}

	private static String read(File file)
	{
		try (InputStream input = new FileInputStream(file))
		{
			ByteArrayOutputStream content = new ByteArrayOutputStream();
			byte[] buffer = new byte[8192];
			int count;
			while ((count = input.read(buffer)) != -1)
				content.write(buffer, 0, count);
			return new String(content.toByteArray(), StandardCharsets.UTF_8);
		}
		catch (Exception ignored)
		{
			return null;
		}
	}

	private static void delete(File file)
	{
		// If it fails, it is sent again at the next launch
		//noinspection ResultOfMethodCallIgnored
		file.delete();
	}
}
