public void removeNonActiveDownloads(boolean isChecked) {
    ArrayList<DownloadInfoRunnable> allDownloads = new ArrayList<DownloadInfoRunnable>();
    allDownloads.addAll(manager.getmErrorList());
    allDownloads.addAll(manager.getmCompletedList());

    for (DownloadInfoRunnable downloadInfoRunnable : allDownloads) {
      downloadInfoRunnable.remove(isChecked);
    }
  }
  public ArrayList<Displayable> getAllActiveDownloads() {
    ArrayList<Displayable> allDownloads = new ArrayList<>();

    for (DownloadInfoRunnable info : getOngoingDownloads()) {
      allDownloads.add(new OngoingDownloadRow(info.getDownload()));
    }

    return allDownloads;
  }
  public ArrayList<Displayable> getAllNonActiveDownloads() {
    ArrayList<Displayable> allNonActive = new ArrayList<>();

    ArrayList<DownloadInfoRunnable> allDownloads = new ArrayList<>();
    allDownloads.addAll(manager.getmErrorList());
    allDownloads.addAll(manager.getmCompletedList());

    for (DownloadInfoRunnable info : allDownloads) {
      allNonActive.add(new NotOngoingDownloadRow(info.getDownload()));
    }

    return allNonActive;
  }
  private NotificationCompat.Builder setNotification(final long id) {

    DownloadInfoRunnable info = getDownload(id);

    final NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this);

    // TODO
    Intent onClick = new Intent();
    onClick.setClassName(
        getPackageName(), /*Aptoide.getConfiguration().*/ getStartActivityClass().getName());
    onClick.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT | Intent.FLAG_ACTIVITY_NEW_TASK);
    onClick.setAction(Intent.ACTION_VIEW);
    onClick.putExtra("fromDownloadNotification", true);

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent onClickAction =
        PendingIntent.getActivity(
            getApplicationContext(), 0, onClick, PendingIntent.FLAG_UPDATE_CURRENT);

    int size = DownloadUtils.dpToPixels(getApplicationContext(), 36);

    Bitmap icon = null;

    try {
      // icon =
      // DownloadUtils.decodeSampledBitmapFromResource(ImageLoader.getInstance().getDiscCache().get(info.getDownload().getIcon()).getAbsolutePath(), size, size);
      icon =
          GlideUtils.downloadOnlyFromCache(
              Aptoide.getContext(), info.getDownload().getIcon(), size, size);
    } catch (Exception e) {
      e.printStackTrace();
    }

    mBuilder.setOngoing(true);
    mBuilder.setContentTitle(
        getString(R.string.aptoide_downloading, Aptoide.getConfiguration().getMarketName()));
    mBuilder.setContentText(info.getDownload().getName());
    if (icon != null) mBuilder.setLargeIcon(icon);
    mBuilder.setSmallIcon(android.R.drawable.stat_sys_download);
    mBuilder.setProgress(0, 0, true);
    mBuilder.setContentIntent(onClickAction);
    // Log.d("download-trace", "ETA: " + info.getEta());
    if (info.getEta() > 0) {
      String remaining = DownloadUtils.formatEta(info.getEta(), "");
      mBuilder.setContentInfo("ETA: " + (!remaining.equals("") ? remaining : "0s"));
    }

    return mBuilder;
  }
  public void resumeDownload(int downloadId) {
    startService(new Intent(getApplicationContext(), DownloadService.class));

    if (mBuilder == null) mBuilder = createDefaultNotification();
    startForeground(-3, mBuilder.build());

    // Log.d("donwload-trace", "setmBuilder: resumeDownload");
    DownloadInfoRunnable info = getDownload(downloadId);
    NotificationCompat.Builder builder = setNotification(downloadId);
    info.setmBuilder(builder);

    info.download();

    startIfStopped();
  }
  public void setReferrer(long id, String referrer) {
    try {

      DownloadInfoRunnable downloadInfoRunnable = downloads.get(id);
      if (downloadInfoRunnable != null) {
        downloadInfoRunnable.getDownloadExecutor().getApk().setReferrer(referrer);
      } else {
        Log.d("AptoideDownloadService", "Downloadinfo for referrer was null");
      }

    } catch (Exception e) {
      e.printStackTrace();
      Log.d("AptoideDownloadService", "error setting referrer");
    }
  }
  private void download(
      long id, Download download, FinishedApk apk, ArrayList<DownloadModel> filesToDownload) {

    DownloadInfoRunnable info = getDownload(id);

    if (download.getCpiUrl() != null) {
      apk.setCpiUrl(download.getCpiUrl());
    }

    if (download.getReferrer() != null) {
      apk.setReferrer(download.getReferrer());
    } else {
      Log.d("AptoideDownloadService", "Creating download with no referrer");
    }

    info.setDownloadExecutor(new DownloadExecutor(apk));
    info.setDownload(download);
    info.setFilesToDownload(filesToDownload);

    boolean update;
    try {
      Aptoide.getContext().getPackageManager().getPackageInfo(download.getPackageName(), 0);
      update = true;
    } catch (PackageManager.NameNotFoundException e) {
      update = false;
    }

    info.setUpdate(update);
    downloads.put(info.getId(), info);
    NotificationCompat.Builder builder = setNotification(info.getId());
    info.setmBuilder(builder);
    info.download();

    if (mBuilder == null) mBuilder = createDefaultNotification();

    startForeground(-3, mBuilder.build());
    startService(new Intent(getApplicationContext(), DownloadService.class));

    startIfStopped();
    Toast.makeText(
            getApplicationContext(),
            getApplicationContext().getString(R.string.starting_download),
            Toast.LENGTH_LONG)
        .show();
  }
  private void updateProgress() {
    Collection<DownloadInfoRunnable> list = getOngoingDownloads();
    list.addAll(manager.getmCompletedList());

    for (DownloadInfoRunnable info : list) {
      if (info.getStatusState() instanceof ActiveState) {
        try {
          info.getmBuilder()
              .setProgress(100, info.getPercentDownloaded(), info.getPercentDownloaded() == 0);
          if (info.getEta() > 0) {
            String remaining = DownloadUtils.formatEta(info.getEta(), "");
            info.getmBuilder().setContentInfo("ETA: " + (!remaining.equals("") ? remaining : "0s"));
          }

          mBuilder = info.getmBuilder();
          ((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
              .notify(-3, mBuilder.build());
        } catch (Exception e) {
          e.printStackTrace();
        }
        return;
      }
    }
  }
  public void stopDownload(long id) {

    DownloadInfoRunnable info = getDownload(id);
    info.remove(true);
  }
  public void startExistingDownload(long id) {
    startService(new Intent(getApplicationContext(), DownloadService.class));

    final NotificationCompat.Builder builder = setNotification(id);

    if (mBuilder == null) mBuilder = createDefaultNotification();
    startForeground(-3, mBuilder.build());

    startIfStopped();

    // Log.d("Aptoide-DownloadManager", "Starting existing download " + id);
    for (final DownloadInfoRunnable info : manager.getmCompletedList()) {
      if (info.getId() == id) {
        final PackageManager packageManager = getPackageManager();
        new Thread(
                new Runnable() {
                  @Override
                  public void run() {
                    for (DownloadModel model : info.getmFilesToDownload()) {
                      try {
                        PackageInfo packageInfo =
                            packageManager.getPackageInfo(
                                info.getDownload().getPackageName(),
                                PackageManager.SIGNATURE_MATCH);
                        if (packageInfo.versionName.equals(info.getDownload().getVersion())) {
                          new Handler(Looper.getMainLooper())
                              .post(
                                  new Runnable() {
                                    @Override
                                    public void run() {
                                      Intent LaunchIntent =
                                          packageManager.getLaunchIntentForPackage(
                                              info.getDownload().getPackageName());
                                      if (LaunchIntent != null) startActivity(LaunchIntent);
                                    }
                                  });
                        } else {
                          throw new PackageManager.NameNotFoundException();
                        }

                      } catch (PackageManager.NameNotFoundException e) {

                        try {
                          String calculatedMd5 =
                              AptoideUtils.Algorithms.md5Calc(new File(model.getDestination()));
                          if (!calculatedMd5.equals(info.getDownload().getMd5())) {
                            // Log.d("download-trace", "Failed Md5 for " +
                            // info.getDownload().getName() + " : " + info.getDestination() + "
                            // calculated " + calculatedMd5 + " vs " + info.getDownload().getMd5());
                            info.setmBuilder(builder);

                            info.download();
                            break;
                          } else {
                            info.autoExecute();
                            // Log.d("download-trace", "Checked Md5 for " +
                            // info.getDownload().getName() + ", application download it's already
                            // completed!");
                            break;
                          }
                        } catch (Exception e1) {
                          e1.printStackTrace();
                        }
                      }
                    }
                  }
                })
            .start();
        return;
      }
    }

    for (DownloadInfoRunnable info : manager.getmErrorList()) {
      if (info.getId() == id) {
        info.setmBuilder(builder);
        info.download();
        return;
      }
    }
  }