package com.apps4fun.nfc.nfckart;

import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.common.SignInButton;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.plus.Plus;
import com.google.android.gms.plus.model.people.Person;

public class MainActivity extends ActionBarActivity
        implements
            OnConnectionFailedListener,
            ConnectionCallbacks,
            OnClickListener {

    public static final String RESTAURANT_ID = "rest_id";
    public static final String TABLE_ID      = "table_id";

    private static final int   RC_SIGN_IN    = 0;
    private GoogleApiClient    mGoogleApiClient;
    private boolean            mIntentInProgress;
    private boolean            mSignInClicked;
    private boolean            isFirstTime = true;
    private ConnectionResult   mConnectionResult;
    private SignInButton       gSignInButton;
    private Person             mCurrnetUser;
    private Intent             mIntent;

    private EditText           mSearch;
    private Button             mSubmit;
    private View               mDefaultView;
    private View               mNtwrkDisabled;
    private View               mTapToView;
    private View               mSignInView;
    private Handler            mHandler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(Plus.API)
                .addScope(Plus.SCOPE_PLUS_LOGIN)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

        gSignInButton   = (SignInButton) findViewById(R.id.sign_in_button);
        mSearch         = (EditText) findViewById(R.id.display_name);
        mSubmit         = (Button) findViewById(R.id.submit);
        mDefaultView    = findViewById(R.id.default_layout);
        mSignInView     = findViewById(R.id.sigin_layout);
        mNtwrkDisabled  = findViewById(R.id.ntwrk_disabled_layout);
        mTapToView      = findViewById(R.id.tap_to_view_layout);

        gSignInButton.setOnClickListener(this);
        mSubmit.setOnClickListener(this);

        mIntent = getIntent();
        mHandler = new Handler();
    }

    private void handleIntent() {
        // TODO Auto-generated method stub

    }

    private boolean isNetworkAvailable() {
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager
                .getActiveNetworkInfo();
        return activeNetworkInfo != null && activeNetworkInfo.isConnected();
    }

    @Override
    protected void onStart() {
        mGoogleApiClient.connect();
        super.onStart();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        if (intent != null) {
            if (intent.getAction().equals(NfcAdapter.ACTION_NDEF_DISCOVERED)) {
                if (mGoogleApiClient.isConnected()) {
                    // proccess rest id and start menu view activity
                    Parcelable[] msg = intent.
                            getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
                    NdefMessage ndefMsg = (NdefMessage) msg[0];
                    NdefRecord[] ndefRecord = ndefMsg.getRecords();
                    ndefRecord[0].getPayload().toString();
                    
                } else {
                    mIntent = intent;
                    displayView(mSignInView);
                }

            } else {
                mIntent = intent;
                if (mGoogleApiClient.isConnected())
                    displayView(mTapToView);
                else
                    displayView(mSignInView);
            }
        }
        super.onNewIntent(intent);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.sign_in_button
                && !mGoogleApiClient.isConnecting()) {
            mSignInClicked = true;
            resolveSignInError();
        } else if (view.getId() == mSubmit.getId()) {
            Intent intent = new Intent(this, MenuDisplayActivity.class);
            intent.putExtra(RESTAURANT_ID, mSearch.getText().toString());
            startActivity(intent);
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int responseCode,
            Intent intent) {
        if (requestCode == RC_SIGN_IN) {
            if (responseCode != RESULT_OK) {
                mSignInClicked = false;
            }

            mIntentInProgress = false;

            if (!mGoogleApiClient.isConnecting()) {
                mGoogleApiClient.connect();
            }
        }
    }

    private void resolveSignInError() {
        if (mConnectionResult == null)
            return;
        if (mConnectionResult.hasResolution()) {
            try {
                mIntentInProgress = true;
                mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
            } catch (SendIntentException e) {
                // The intent was canceled before it was sent. Return to the
                // default
                // state and attempt to connect to get an updated
                // ConnectionResult.
                mIntentInProgress = false;
                mGoogleApiClient.connect();
            }
        } else {
            GooglePlayServicesUtil.getErrorDialog(
                    mConnectionResult.getErrorCode(), this, RC_SIGN_IN).show();

        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        if(!mSignInClicked && !isNetworkAvailable())
            displayView(mNtwrkDisabled);
        else
            displayView(mSignInView);
        if (!mIntentInProgress) {
            // Store the ConnectionResult so that we can use it later when the
            // user clicks
            // 'sign-in'.
            mConnectionResult = result;

            if (mSignInClicked) {
                // The user has already clicked 'sign-in' so we attempt to
                // resolve all
                // errors until the user is signed in, or they cancel.
                resolveSignInError();
            }
        }

    }

    private void displayView(View view) {
        if (isFirstTime) {
            final View v = view;
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    displayView(v);
                }
            }, 2000);
            isFirstTime = false;
            return;
        }
        mNtwrkDisabled.setVisibility(View.GONE);
        mSignInView.setVisibility(View.GONE);
        mDefaultView.setVisibility(View.GONE);
        mTapToView.setVisibility(View.GONE);

        view.setVisibility(View.VISIBLE);
    }

    @Override
    public void onConnected(Bundle arg0) {
        mSignInClicked = false;
        onNewIntent(mIntent);
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onStop() {
        if (mGoogleApiClient != null)
            mGoogleApiClient.disconnect();
        super.onStop();
    }

}
