package cancer.findyourfate.com;

import java.io.IOException;

 
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log; 
import android.widget.Button;  

import com.google.android.gms.gcm.GoogleCloudMessaging;
 
public class RegisterActivity extends AppCompatActivity {
 
  Button btnGCMRegister;
  Button btnAppShare;
  GoogleCloudMessaging gcm;
  Context context;
  String regId; 
 
  public static final String PROPERTY_REG_ID  = "regId";
  private static final String APP_VERSION = "appVersion";
 
  static final String TAG = "Register Activity";
 
  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
  setContentView(R.layout.home);
   getSupportActionBar().setTitle(
		   Html.fromHtml("<font color=\"#ffffff\" size=\"25px\"><b>"+"Cancer"+"</b></font>"));
  			context = getApplicationContext(); 
           regId = registerGCM();
   }
  public String registerGCM() {
 
    gcm = GoogleCloudMessaging.getInstance(this);
    regId = getRegistrationId(context);
 
    if (TextUtils.isEmpty(regId)) {
 
      registerInBackground();
 
      } else {
      }
    
    return regId;
  }
 
  private String getRegistrationId(Context context) {
    final SharedPreferences prefs = getGCMPreferences(context);
         
    String registrationId = prefs.getString(PROPERTY_REG_ID , "");
    if (registrationId.isEmpty()) {
      Log.i(TAG, "Registration not found.");
      return "";
    }
    int registeredVersion = prefs.getInt(APP_VERSION, Integer.MIN_VALUE);
    int currentVersion = getAppVersion(context);
    if (registeredVersion != currentVersion) {
     // Log.i(TAG, "App version changed.");
      return "";
    }
    return registrationId;
  }
  private SharedPreferences getGCMPreferences(Context context) {
	    // This sample app persists the registration ID in shared preferences, but
	    // how you store the regID in your app is up to you.
	    return getSharedPreferences(RegisterActivity.class.getSimpleName(),
	            Context.MODE_PRIVATE);
	}
  private static int getAppVersion(Context context) {
    try {
      PackageInfo packageInfo = context.getPackageManager()
          .getPackageInfo(context.getPackageName(), 0);
      return packageInfo.versionCode;
    } catch (NameNotFoundException e) {
      Log.d("RegisterActivity",
          "I never expected this! Going down, going down!" + e);
      throw new RuntimeException(e);
    }
  }
 
  private void registerInBackground() {
    new AsyncTask<Void, Void, String>() {
      @Override
      protected String doInBackground(Void... params) {
        String msg = "";
        try {
          if (gcm == null) {
            gcm = GoogleCloudMessaging.getInstance(context);
          }
          regId = gcm.register(Config.GOOGLE_PROJECT_ID);
          Log.d("RegisterActivity", "registerInBackground - regId: " + regId);
          msg = "Device registered, registration ID=" + regId;
 
          storeRegistrationId(context, regId);
           Intent i = new Intent(getApplicationContext(), MainActivityfirst.class);
              i.putExtra("regId", regId);
             // Log.d("RegisterActivity",
              //    "onClick of Share: Before starting main activity." +regId);
              startActivity(i);
              finish();
       
        } catch (IOException ex) {
          msg = "Error :" + ex.getMessage();
          Log.d("RegisterActivity", "Error: " + msg);
          Intent i = new Intent(getApplicationContext(), MainActivityfirst.class);
          i.putExtra("regId", regId);
         // Log.d("RegisterActivity",
          //    "onClick of Share: Before starting main activity." +regId);
          startActivity(i);
          finish();
        }
        Log.d("RegisterActivity", "AsyncTask completed: " + msg);
        return msg;
      }
 
      @Override
      protected void onPostExecute(String msg) {
      // Toast.makeText(getApplicationContext(),  "Registered with GCM Server." + msg, Toast.LENGTH_LONG).show();
      }
    }.execute(null, null, null);
  }
 
  private void storeRegistrationId(Context context, String regId) {
    final SharedPreferences prefs = getSharedPreferences(
        MainActivityfirst.class.getSimpleName(), Context.MODE_PRIVATE);
    int appVersion = getAppVersion(context);
    Log.i(TAG, "Saving regId on app version " + appVersion);
    SharedPreferences.Editor editor = prefs.edit();
    editor.putString(PROPERTY_REG_ID , regId);
    editor.putInt(APP_VERSION, appVersion);
    editor.commit();
  }
  
  @Override
	public void onBackPressed() {
	AlertDialog.Builder builder = new AlertDialog.Builder(this);
	builder.setTitle("Exit!");
	builder.setMessage("Are you sure you want to exit from Cancer app?")
	       .setCancelable(false)
	       .setIcon(R.drawable.alert)
	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	         	Intent intent = new Intent(Intent.ACTION_MAIN);
			    	intent.addCategory(Intent.CATEGORY_HOME);
			    	intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			    	startActivity(intent);
	        }
	       })
	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
	        public void onClick(DialogInterface dialog, int id) {
	         dialog.cancel();
	      }
	       });
	AlertDialog alert = builder.create();
	alert.show();
  		}  
  }