package co.islovely.pinpoint;

import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Build;
import android.os.Build.VERSION;
import android.util.DisplayMetrics;
import org.json.JSONException;
import org.json.JSONObject;

public class DeviceMetrics {
  private DisplayMetrics displayMetrics;

  private PackageManager packageManager;

  public DeviceMetrics(PackageManager packageManager, DisplayMetrics displayMetrics) {
    this.displayMetrics = displayMetrics;
    this.packageManager = packageManager;
  }

  public JSONObject toJSON() {
    JSONObject
        json = new JSONObject(),
        launcher = new JSONObject(),
        screen = new JSONObject(),
        sdk = new JSONObject();

    try {
      json.put("manufacturer", Build.MANUFACTURER);
      json.put("model", Build.MODEL);

      sdk.put("release", Build.VERSION.RELEASE);
      sdk.put("version", Build.VERSION.SDK_INT);
      json.put("sdk", sdk);

      if (null != this.displayMetrics) {
        screen.put("height", this.displayMetrics.heightPixels);
        screen.put("width", this.displayMetrics.widthPixels);
        screen.put("density", this.displayMetrics.density);
        json.put("screen", screen);
      }

      if (null != this.packageManager) {
        ActivityInfo activityInfo = (this.packageManager.resolveActivity(
            new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME),
            PackageManager.MATCH_DEFAULT_ONLY
        )).activityInfo;

        launcher.put("packageName", activityInfo.packageName);
        launcher.put("name", activityInfo.name);

        PackageInfo packageInfo = null;
        try {
          packageInfo = this.packageManager.getPackageInfo(activityInfo.packageName, 0);
        } catch (NameNotFoundException exception) {
          Pinpoint.log("Could not find additional information on launcher.");
        }

        if (null != packageInfo) {
          launcher.put("firstInstalledAt", packageInfo.firstInstallTime);
          launcher.put("lastUpdatedAt", packageInfo.lastUpdateTime);
          launcher.put("versionName", packageInfo.versionName);
          launcher.put("versionCode", packageInfo.versionCode);
        }

        json.put("launcher", launcher);
      }
    } catch (JSONException exception) {
      Pinpoint.log("Could not create JSONObject from DeviceMetrics.");
    }

    return json;
  }
}
