content: package bscorp.appbase;
  
  import android.animation.Animator;
  import android.animation.AnimatorListenerAdapter;
  import android.annotation.TargetApi;
  import android.app.LoaderManager;
  import android.app.ProgressDialog;
  import android.content.CursorLoader;
  import android.content.Intent;
  import android.content.IntentSender;
  import android.content.Loader;
  import android.content.pm.PackageManager;
  import android.database.Cursor;
  import android.net.Uri;
  import android.os.AsyncTask;
  import android.os.Build;
  import android.os.Bundle;
  import android.provider.ContactsContract;
  import android.support.annotation.NonNull;
  import android.support.design.widget.Snackbar;
  import android.support.v7.app.AppCompatActivity;
  import android.text.TextUtils;
  import android.util.Log;
  import android.view.KeyEvent;
  import android.view.View;
  import android.view.WindowManager;
  import android.view.inputmethod.EditorInfo;
  import android.widget.ArrayAdapter;
  import android.widget.AutoCompleteTextView;
  import android.widget.Button;
  import android.widget.EditText;
  import android.widget.TextView;
  import android.widget.Toast;
  
  import com.facebook.CallbackManager;
  import com.facebook.FacebookCallback;
  import com.facebook.FacebookException;
  import com.facebook.FacebookSdk;
  import com.facebook.GraphRequest;
  import com.facebook.GraphResponse;
  import com.facebook.login.LoginResult;
  import com.facebook.login.widget.LoginButton;
  import com.google.android.gms.common.ConnectionResult;
  import com.google.android.gms.common.Scopes;
  import com.google.android.gms.common.SignInButton;
  import com.google.android.gms.common.api.GoogleApiClient;
  import com.google.android.gms.common.api.Scope;
  import com.google.android.gms.plus.Plus;
  import com.google.android.gms.plus.model.people.Person;
  
  import org.json.JSONObject;
  
  import java.util.ArrayList;
  import java.util.Arrays;
  import java.util.List;
  
  import utils.Constants;
  import utils.ValidateUserInfo;
  
  import static android.Manifest.permission.READ_CONTACTS;
  
  /**
   * A login screen that offers login via email/password.
   */
  public class LoginActivity extends AppCompatActivity implements
          GoogleApiClient.ConnectionCallbacks,
          GoogleApiClient.OnConnectionFailedListener,
          View.OnClickListener, LoaderManager.LoaderCallbacks<Cursor> {
  
      /**
       * Id to identity READ_CONTACTS permission request.
       */
      private static final int REQUEST_READ_CONTACTS = 0;
  
      /**
       * A dummy authentication store containing known user names and passwords.
       * TODO: remove after connecting to a real authentication system.
       */
      private static final String[] DUMMY_CREDENTIALS = new String[]{
              "foo@example.com:hello", "bar@example.com:world"
      };
      /**
       * Keep track of the login task to ensure we can cancel it if requested.
       */
      private UserLoginTask mAuthTask = null;
  
      // UI references.
      private AutoCompleteTextView mEmailView;
      private EditText mPasswordView;
      private View mProgressView;
      private View mLoginFormView;
  
      /* Request code used to invoke sign in user interactions. */
      private static final int RC_SIGN_IN = 0;
      /* Client used to interact with Google APIs. */
      private GoogleApiClient mGoogleApiClient;
  
      /* Is there a ConnectionResult resolution in progress? */
      private boolean mIsResolving = false;
      /* Should we automatically resolve ConnectionResults when possible? */
      private boolean mShouldResolve = false;
  
      private CallbackManager callbackManager;
  
      private SignInButton mPlusSignInButton;
      private Button mEmailSignInButton;
  
      private TextView txt_create, txt_forgot;
      private LoginButton facebookLoginButton;
  
      ProgressDialog ringProgressDialog;
  
      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          FacebookSdk.sdkInitialize(getApplicationContext());
          setContentView(R.layout.activity_login);
  
          initInstances();
      }
  
      private void initInstances() {
          // Set up the login form.
          mLoginFormView = findViewById(R.id.login_form);
          mProgressView = findViewById(R.id.login_progress);
  
          mEmailView = (AutoCompleteTextView) findViewById(R.id.txt_email);
          populateAutoComplete();
  
          mPasswordView = (EditText) findViewById(R.id.txt_password);
          mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
              @Override
              public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                  if (id == R.id.login || id == EditorInfo.IME_NULL) {
                      attemptLogin();
                      return true;
                  }
                  return false;
              }
          });
  
          txt_create = (TextView) findViewById(R.id.txt_create);
          txt_create.setOnClickListener(this);
  
          txt_forgot = (TextView) findViewById(R.id.txt_forgot);
          txt_forgot.setOnClickListener(this);
  
          mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
          mEmailSignInButton.setOnClickListener(this);
  
          //Google+ Login
          mPlusSignInButton = (SignInButton) findViewById(R.id.g_sign_in_button);
          mPlusSignInButton.setSize(SignInButton.SIZE_WIDE);
          mPlusSignInButton.setOnClickListener(this);
  
          mGoogleApiClient = new GoogleApiClient.Builder(this)
                  .addConnectionCallbacks(this)
                  .addOnConnectionFailedListener(this)
                  .addApi(Plus.API)
                  .addScope(new Scope(Scopes.PROFILE))
                  .build();
  
          //Facebook Login
          facebookLoginButton = (LoginButton)findViewById(R.id.f_sign_in_button);
          facebookLoginButton.setReadPermissions(Arrays.asList("public_profile, email, user_birthday, user_friends"));
  
          callbackManager = CallbackManager.Factory.create();
  
          // Callback registration
          facebookLoginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
              @Override
              public void onSuccess(LoginResult loginResult) {
                  // App code
                  GraphRequest request = GraphRequest.newMeRequest(
                          loginResult.getAccessToken(),
                          new GraphRequest.GraphJSONObjectCallback() {
                              @Override
                              public void onCompleted(
                                      JSONObject object,
                                      GraphResponse response) {
                                  // Application code
                              }
                          });
  
                  Bundle parameters = new Bundle();
                  parameters.putString("fields", "id,name,email,gender, birthday");
                  request.setParameters(parameters);
                  request.executeAsync();
              }
  
              @Override
              public void onCancel() {
                  Toast.makeText(LoginActivity.this, "User cancelled", Toast.LENGTH_SHORT).show();
              }
  
              @Override
              public void onError(FacebookException exception) {
                  Toast.makeText(LoginActivity.this, "Error on Login, check your facebook app_id", Toast.LENGTH_LONG).show();
              }
          });
  
          this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
      }
  
      private void populateAutoComplete() {
          if (!mayRequestContacts()) {
              return;
          }
  
          getLoaderManager().initLoader(0, null, this);
      }
  
      private boolean mayRequestContacts() {
          if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
              return true;
          }
          if (checkSelfPermission(READ_CONTACTS) == PackageManager.PERMISSION_GRANTED) {
              return true;
          }
          if (shouldShowRequestPermissionRationale(READ_CONTACTS)) {
              Snackbar.make((LinearLayout)findViewById(R.id.ll_main), R.string.permission_rationale, Snackbar.LENGTH_INDEFINITE)
                      .setAction(android.R.string.ok, new View.OnClickListener() {
                          @Override
                          @TargetApi(Build.VERSION_CODES.M)
                          public void onClick(View v) {
                              requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
                          }
                      }).show();
          } else {
              requestPermissions(new String[]{READ_CONTACTS}, REQUEST_READ_CONTACTS);
          }
          return false;
      }
  
      /**
       * Callback received when a permissions request has been completed.
       */
      @Override
      public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
                                             @NonNull int[] grantResults) {
          if (requestCode == REQUEST_READ_CONTACTS) {
              if (grantResults.length == 1 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                  populateAutoComplete();
              }
          }
      }
  
      /**
       * Attempts to sign in or register the account specified by the login form.
       * If there are form errors (invalid email, missing fields, etc.), the
       * errors are presented and no actual login attempt is made.
       */
      private void attemptLogin() {
          if (mAuthTask != null) {
              return;
          }
  
          // Reset errors.
          mEmailView.setError(null);
          mPasswordView.setError(null);
  
          // Store values at the time of the login attempt.
          String email = mEmailView.getText().toString();
          String password = mPasswordView.getText().toString();
  
          boolean cancel = false;
          View focusView = null;
  
          ValidateUserInfo validateUserInfo = new ValidateUserInfo();
  
          // Check for a valid password, if the user entered one.
          if (!TextUtils.isEmpty(password) && !validateUserInfo.isPasswordValid(password)) {
              mPasswordView.setError(getString(R.string.error_invalid_password));
              focusView = mPasswordView;
              cancel = true;
          }
  
          // Check for a valid email address.
          if (TextUtils.isEmpty(email)) {
              mEmailView.setError(getString(R.string.error_field_required));
              focusView = mEmailView;
              cancel = true;
          } else if (!validateUserInfo.isEmailValid(email)) {
              mEmailView.setError(getString(R.string.error_invalid_email));
              focusView = mEmailView;
              cancel = true;
          }
  
          if (cancel) {
              // There was an error; don't attempt login and focus the first
              // form field with an error.
              focusView.requestFocus();
          } else {
              // Show a progress spinner, and kick off a background task to
              // perform the user login attempt.
              showProgress(true);
              mAuthTask = new UserLoginTask(email, password);
              mAuthTask.execute((Void) null);
          }
      }
  
      /**
       * Shows the progress UI and hides the login form.
       */
      @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
      private void showProgress(final boolean show) {
          // On Honeycomb MR2 we have the ViewPropertyAnimator APIs, which allow
          // for very easy animations. If available, use these APIs to fade-in
          // the progress spinner.
          if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
              int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
  
              mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
              mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                      show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                  @Override
                  public void onAnimationEnd(Animator animation) {
                      mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                  }
              });
  
              mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
              mProgressView.animate().setDuration(shortAnimTime).alpha(
                      show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                  @Override
                  public void onAnimationEnd(Animator animation) {
                      mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                  }
              });
          } else {
              // The ViewPropertyAnimator APIs are not available, so simply show
              // and hide the relevant UI components.
              mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
              mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
          }
      }
  
      @Override
      public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
          return new CursorLoader(this,
                  // Retrieve data rows for the device user's 'profile' contact.
                  Uri.withAppendedPath(ContactsContract.Profile.CONTENT_URI,
                          ContactsContract.Contacts.Data.CONTENT_DIRECTORY), ProfileQuery.PROJECTION,
  
                  // Select only email addresses.
                  ContactsContract.Contacts.Data.MIMETYPE +
                          " = ?", new String[]{ContactsContract.CommonDataKinds.Email
                  .CONTENT_ITEM_TYPE},
  
                  // Show primary email addresses first. Note that there won't be
                  // a primary email address if the user hasn't specified one.
                  ContactsContract.Contacts.Data.IS_PRIMARY + " DESC");
      }
  
      @Override
      public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
          List<String> emails = new ArrayList<>();
          cursor.moveToFirst();
          while (!cursor.isAfterLast()) {
              emails.add(cursor.getString(ProfileQuery.ADDRESS));
              cursor.moveToNext();
          }
  
          addEmailsToAutoComplete(emails);
      }
  
      @Override
      public void onLoaderReset(Loader<Cursor> cursorLoader) {
  
      }
  
      private interface ProfileQuery {
          String[] PROJECTION = {
                  ContactsContract.CommonDataKinds.Email.ADDRESS,
                  ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
          };
  
          int ADDRESS = 0;
          int IS_PRIMARY = 1;
      }
  
  
      private void addEmailsToAutoComplete(List<String> emailAddressCollection) {
          //Create adapter to tell the AutoCompleteTextView what to show in its dropdown list.
          ArrayAdapter<String> adapter =
                  new ArrayAdapter<>(LoginActivity.this,
                          android.R.layout.simple_dropdown_item_1line, emailAddressCollection);
  
          mEmailView.setAdapter(adapter);
      }
  
      @Override
      public void onClick(View v) {
          String email = mEmailView.getText().toString();
  
          switch (v.getId()) {
              case R.id.g_sign_in_button:
                  onSignInClicked();
                  break;
              case R.id.email_sign_in_button:
                  attemptLogin();
                  break;
              case R.id.txt_create:
                  Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                  intent.putExtra(Constants.TAG_EMAIL, email);
                  startActivity(intent);
                  finish();
                  break;
              case R.id.txt_forgot:
                  Intent intentForgot = new Intent(LoginActivity.this, ForgotPassActivity.class);
                  intentForgot.putExtra(Constants.TAG_EMAIL, email);
                  startActivity(intentForgot);
                  finish();
                  break;
          }
      }
  
      private void onSignInClicked() {
  //        toastLoading.show();
          // User clicked the sign-in button, so begin the sign-in process and automatically
          // attempt to resolve any errors that occur.
          ringProgressDialog = ProgressDialog.show(LoginActivity.this, "Connecting...", "Atempting to connect", true);
          ringProgressDialog.setCancelable(false);
          new Thread(new Runnable() {
              @Override
              public void run() {
                  try {
                      mShouldResolve = true;
                      mGoogleApiClient.connect();
                  } catch (Exception e) {
                      ringProgressDialog.dismiss();
                      e.printStackTrace();
                  }
              }
          }).start();
      }
  
      @Override
      public void onConnected(Bundle bundle) {
          mShouldResolve = false;
          getProfileInformation();
      }
  
      @Override
      public void onConnectionSuspended(int arg0) {
          ringProgressDialog.dismiss();
          mGoogleApiClient.connect();
      }
  
      @Override
      public void onConnectionFailed(ConnectionResult connectionResult) {
          // Could not connect to Google Play Services.  The user needs to select an account,
          // grant permissions or resolve an error in order to sign in. Refer to the javadoc for
          // ConnectionResult to see possible error codes.
          Log.d(Constants.TAG_LOGIN, "onConnectionFailed:" + connectionResult);
          ringProgressDialog.dismiss();
  
          if (!mIsResolving && mShouldResolve) {
              if (connectionResult.hasResolution()) {
                  try {
                      connectionResult.startResolutionForResult(this, RC_SIGN_IN);
                      mIsResolving = true;
                  } catch (IntentSender.SendIntentException e) {
                      Log.e(Constants.TAG_LOGIN, "Could not resolve ConnectionResult.", e);
                      Toast.makeText(LoginActivity.this, "Could not resolve ConnectionResult", Toast.LENGTH_LONG).show();
                      mIsResolving = false;
                  }
              } else {
                  // Could not resolve the connection result, show the user an
                  // error dialog.
                  Toast.makeText(LoginActivity.this, "Error on Login, check your google + login method", Toast.LENGTH_LONG).show();
              }
          } else {
              // Show the signed-out UI
          }
      }
  
      /**
       * Fetching user's information name, email, profile pic
       * */
      private void getProfileInformation() {
          ringProgressDialog.dismiss();
          if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
              Person currentPerson = Plus.PeopleApi
                      .getCurrentPerson(mGoogleApiClient);
              String personName = currentPerson.getDisplayName();
              String personPhotoUrl = currentPerson.getImage().getUrl();
              String personGooglePlusProfile = currentPerson.getUrl();
              String birth = currentPerson.getBirthday();
              String email = Plus.AccountApi.getAccountName(mGoogleApiClient);
  
              // by default the profile url gives 50x50 px image only
              // we can replace the value with whatever dimension we want by
              // replacing sz=X
  //                personPhotoUrl = personPhotoUrl.substring(0,
  //                        personPhotoUrl.length() - 2)
  //                        + PROFILE_PIC_SIZE;
  
              //new LoadProfileImage().execute(personPhotoUrl);
  
          } else {
              Toast.makeText(getApplicationContext(),
                      "Person information is null", Toast.LENGTH_LONG).show();
          }
      }
  
      /**
       * Represents an asynchronous login/registration task used to authenticate
       * the user.
       */
      public class UserLoginTask extends AsyncTask<Void, Void, Boolean> {
  
          private final String mEmail;
          private final String mPassword;
  
          UserLoginTask(String email, String password) {
              mEmail = email;
              mPassword = password;
          }
  
          @Override
          protected Boolean doInBackground(Void... params) {
              // TODO: attempt authentication against a network service.
  
              try {
                  // Simulate network access.
                  Thread.sleep(2000);
              } catch (InterruptedException e) {
                  return false;
              }
  
              for (String credential : DUMMY_CREDENTIALS) {
                  String[] pieces = credential.split(":");
                  if (pieces[0].equals(mEmail)) {
                      // Account exists, return true if the password matches.
                      return pieces[1].equals(mPassword);
                  }
              }
  
              // TODO: register the new account here.
              return true;
          }
  
          @Override
          protected void onPostExecute(final Boolean success) {
              mAuthTask = null;
              showProgress(false);
  
              if (success) {
                  startActivity(new Intent(LoginActivity.this, MainActivity.class));
                  finish();
              } else {
                  mPasswordView.setError(getString(R.string.error_incorrect_password));
                  mPasswordView.requestFocus();
              }
          }
  
          @Override
          protected void onCancelled() {
              mAuthTask = null;
              showProgress(false);
          }
      }
  
      @Override
      protected void onStop() {
          super.onStop();
          if (mGoogleApiClient.isConnected()) {
              mGoogleApiClient.disconnect();
          }
      }
  }
  
  