package com.cygnusa.hyperm.library;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.text.Html;

import com.cygnusa.hyperm.R;
import com.cygnusa.hyperm.util.TransparentProgressDialog;


public class UpdateDialog {


    public static void show(final Context context, String content, final String downloadUrl) {
        if (isContextValid(context)) {

            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(context.getResources().getString(R.string.alert_update_title));
            builder.setMessage(Html.fromHtml(content))
                    .setPositiveButton(context.getResources().getString(R.string.alert_update), new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            new TransparentProgressDialog(context).show();
                            goToDownload(context, downloadUrl);
                        }
                    }).setNegativeButton("Cancel", null);


            AlertDialog dialog = builder.create();

            dialog.setCanceledOnTouchOutside(false);
            dialog.show();
        }
    }

    private static boolean isContextValid(Context context) {
        return context instanceof Activity && !((Activity) context).isFinishing();
    }


    private static void goToDownload(Context context, String downloadUrl) {

        Intent intent = new Intent(context, DownloadService.class);
        intent.putExtra(Constants.APK_DOWNLOAD_URL, downloadUrl);
        context.startService(intent);

    }
}
