Subversion Repositories SmartDukaan

Rev

Rev 14792 | Rev 16080 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.saholic.profittill.main;


import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.facebook.Session;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.plus.Plus;
import com.mixpanel.android.mpmetrics.MixpanelAPI;
import com.saholic.profittill.Constants.ProfitTillConstants;
import com.saholic.profittill.R;
import com.saholic.profittill.Utils.UtilityFunctions;
import com.saholic.profittill.navigationdrawer.NavDrawerItem;
import com.saholic.profittill.navigationdrawer.NavDrawerListAdapter;
import com.testin.agent.TestinAgent;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


public class MainActivity extends ActionBarActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;
    public GoogleApiClient mGoogleApiClient;
    SharedPreferences userData;
    SharedPreferences apiData;
    boolean glogout;
    SharedPreferences.Editor userDataEditor;
    SharedPreferences.Editor apiSettingsEditor;
    SharedPreferences.Editor inviteDataEditor;
    SharedPreferences inviteData;
    private String[] navMenuTitles;
    private TypedArray navMenuIcons;
    String type1;
    private ArrayList<NavDrawerItem> navDrawerItems;
    private NavDrawerListAdapter adapter;
    int flag;
    boolean shouldGoInvisible;
    int titleVisible;
    StringBuilder subtag,sb;
    String userIdAffliate;
    Date dateAffliate;
    String stringDateAffliate;
    SimpleDateFormat dateFormatAffliate;
    String redirectUrl;
    MixpanelAPI mixpanel;
    String notificationURL;
    ArrayList<NameValuePair> nameValuePairsGcm;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TestinAgent.init(this);
        userData = getApplicationContext().getSharedPreferences("User_Data", MODE_PRIVATE);
        apiData = getApplicationContext().getSharedPreferences("API_Data", MODE_PRIVATE);
        userDataEditor = userData.edit();
        apiSettingsEditor = apiData.edit();
        inviteData = getApplicationContext().getSharedPreferences("Invite_Data", Context.MODE_PRIVATE);
        inviteDataEditor = inviteData.edit();
        TestinAgent.setUserInfo(userData.getString("id",""));
        mixpanel = MixpanelAPI.getInstance(getApplicationContext(), ProfitTillConstants.MIX_PANEL_TOKEN);
        type1 = userData.getString("type",null);

        if(getIntent().getAction()=="20"){
            flag=20;
            notificationURL = String.valueOf(getIntent().getData());
            nameValuePairsGcm = new ArrayList<>();
            nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id","")));
            nameValuePairsGcm.add(new BasicNameValuePair("cid",getIntent().getExtras().getString("cid")));
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp", UtilityFunctions.notificationDate()));
            nameValuePairsGcm.add(new BasicNameValuePair("result","opened"));
            getIntent().getExtras().remove("cid");
            new NotificationOpenedData().execute(nameValuePairsGcm);
        }else if(getIntent().getAction()=="15"){
            flag=15;
            nameValuePairsGcm = new ArrayList<>();
            nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id","")));
            nameValuePairsGcm.add(new BasicNameValuePair("cid",getIntent().getExtras().getString("cid")));
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp",UtilityFunctions.notificationDate()));
            nameValuePairsGcm.add(new BasicNameValuePair("result","opened"));
            getIntent().getExtras().remove("cid");
            new NotificationOpenedData().execute(nameValuePairsGcm);
        }else if(getIntent().getAction()=="7"){
            flag=7;
            nameValuePairsGcm = new ArrayList<>();
            nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id","")));
            nameValuePairsGcm.add(new BasicNameValuePair("cid",getIntent().getExtras().getString("cid")));
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp",UtilityFunctions.notificationDate()));
            nameValuePairsGcm.add(new BasicNameValuePair("result","opened"));
            getIntent().getExtras().remove("cid");
            new NotificationOpenedData().execute(nameValuePairsGcm);
        }else if(getIntent().getAction()=="6"){
            flag=6;
            nameValuePairsGcm = new ArrayList<>();
            nameValuePairsGcm.add(new BasicNameValuePair("user_id",userData.getString("id","")));
            nameValuePairsGcm.add(new BasicNameValuePair("cid",getIntent().getExtras().getString("cid")));
            nameValuePairsGcm.add(new BasicNameValuePair("timestamp",UtilityFunctions.notificationDate()));
            nameValuePairsGcm.add(new BasicNameValuePair("result","opened"));
            getIntent().getExtras().remove("cid");
            new NotificationOpenedData().execute(nameValuePairsGcm);
        }else {
            Bundle i = getIntent().getExtras();
            if (i != null) {
                flag = Integer.parseInt(i.getString("displayView"));
                if (flag == 31) {
                    redirectUrl = i.getString("redirectUrl");
                }
            }
        }



        getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.WHITE));
        getSupportActionBar().setIcon(R.drawable.logo_cirlce_1);
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);

        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class
                    .getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception ex) {
            Log.d("Exception","Message"+ex);
        }

        if(type1!=null && type1.equalsIgnoreCase("google")) {
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).addApi(Plus.API)
                    .addScope(Plus.SCOPE_PLUS_LOGIN).build();
            mGoogleApiClient.connect();
        }

        /*mTitle = mDrawerTitle = getTitle();*/
        // load slide menu items
        navMenuTitles = getResources().getStringArray(R.array.nav_drawer_items);

        // nav drawer icons from resources
        navMenuIcons = getResources()
                .obtainTypedArray(R.array.nav_drawer_icons);

        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
        mDrawerLayout.setBackgroundColor(getResources().getColor(R.color.White));
        navDrawerItems = new ArrayList<NavDrawerItem>();



        navDrawerItems.add(new NavDrawerItem(navMenuTitles[0], navMenuIcons.getResourceId(0, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[1], navMenuIcons.getResourceId(1, 0)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[2], navMenuIcons.getResourceId(2, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[3], navMenuIcons.getResourceId(3, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[4], navMenuIcons.getResourceId(4, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[5], navMenuIcons.getResourceId(5, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[6], navMenuIcons.getResourceId(6, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[7], navMenuIcons.getResourceId(7, -1)));
        navDrawerItems.add(new NavDrawerItem(navMenuTitles[8], navMenuIcons.getResourceId(8, -1)));
       /* navDrawerItems.add(new NavDrawerItem(navMenuTitles[9], navMenuIcons.getResourceId(8, -1)));*/
        navMenuIcons.recycle();

        mDrawerList.setOnItemClickListener(new SlideMenuClickListener());

        // setting the nav drawer list adapter
        adapter = new NavDrawerListAdapter(getApplicationContext(),navDrawerItems);
        mDrawerList.setAdapter(adapter);

        // enabling action bar app icon and behaving it as toggle button
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.menubutton, //nav menu toggle icon
                R.string.hello_world, // nav drawer open - description for accessibility
                R.string.hello_world// nav drawer close - description for accessibility
        ) {
            public void onDrawerClosed(View view) {
                if(titleVisible!=0) {
                    if(titleVisible==1)
                        getSupportActionBar().setCustomView(R.layout.actionbarmyfavorites);

                    if(titleVisible==2)
                        getSupportActionBar().setCustomView(R.layout.actionbarprefernces);

                    if(titleVisible==3)
                        getSupportActionBar().setCustomView(R.layout.actionbarmywallet);

                    if(titleVisible==4)
                        getSupportActionBar().setCustomView(R.layout.actionbarmyorders);

                    if(titleVisible==5)
                        getSupportActionBar().setCustomView(R.layout.actionbarpendingcashback);

                    if(titleVisible==6)
                        getSupportActionBar().setCustomView(R.layout.actionbarmyprofile);


                }
                else{
                    if (getTitle().equals("Deals")) {
                        getSupportActionBar().setCustomView(R.layout.actionbardeals);
                    }
                    if (getTitle().equals("Saholic") || getTitle().equals("Flipkart") || getTitle().equals("Snapdeal") || getTitle().equals("Amazon")) {
                        getSupportActionBar().setCustomView(R.layout.actionbarprofittill);
                    }
                    if (getTitle().equals("FAQ")) {
                        getSupportActionBar().setCustomView(R.layout.actionbaraboutus);
                    }
                    if (getTitle().equals("Contact Us")) {
                        getSupportActionBar().setCustomView(R.layout.actionbarcontactus);
                    }
                    if (getTitle().equals("Search")) {
                        getSupportActionBar().setCustomView(R.layout.actionbarsearch);
                    }
                    if (getTitle().equals("How It Works")) {
                        getSupportActionBar().setCustomView(R.layout.actionbarhowitworks);
                    }
                }
                shouldGoInvisible = false;
                invalidateOptionsMenu();
            }

            public void onDrawerOpened(View drawerView) {
                getSupportActionBar().setCustomView(R.layout.actionbarprofittill);
                shouldGoInvisible = true;
                invalidateOptionsMenu();
            }
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {


            }

        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {

                if (flag == 7) {
                    getSupportActionBar().setCustomView(R.layout.actionbarhowitworks);
                    displayView(flag);
                } else if (flag == 6) {
                    getSupportActionBar().setCustomView(R.layout.actionbarcontactus);
                    displayView(flag);
                } else if (flag == 15) {
                    getSupportActionBar().setCustomView(R.layout.actionbarmyprofile);
                    MyProfile myProfile = new MyProfile();
                    this.getFragmentManager().beginTransaction()
                            .replace(R.id.frame_container, myProfile, "Mike")
                            .addToBackStack(null)
                            .commit();
                }else if (flag == 20) {
                    getSupportActionBar().setCustomView(R.layout.actionbardeals);
                    JSONObject propsNotification = new JSONObject();
                    try {
                        mixpanel.identify(userData.getString("id",null));
                        propsNotification.put("Screen", "Notification Url opened");
                        mixpanel.track("Notification Opened", propsNotification);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Bundle args = new Bundle();
                    DealsHomeFragment notifcationFragment = new DealsHomeFragment();
                    args.putString("key", notificationURL);
                    this.getFragmentManager().beginTransaction()
                            .replace(R.id.frame_container, notifcationFragment, "Mike")
                            .addToBackStack(null)
                            .commit();
                    notifcationFragment.setArguments(args);
                }else if (flag == 31) {
                    getSupportActionBar().setCustomView(R.layout.actionbardeals);
                    Bundle args = new Bundle();
                    DealsHomeFragment redirectUrlFragment = new DealsHomeFragment();
                    args.putString("key", redirectUrl);
                    this.getFragmentManager().beginTransaction()
                            .replace(R.id.frame_container, redirectUrlFragment, "Mike")
                            .addToBackStack(null)
                            .commit();
                    redirectUrlFragment.setArguments(args);
                }else {
                    getSupportActionBar().setCustomView(R.layout.actionbardeals);
                    displayView(0);
                }

        }
    }

    /**
     * Slide menu item click listener
     * */
    private class SlideMenuClickListener implements
            ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                                long id) {
            // display view for selected nav drawer item
            displayView(position);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mainMenu=menu;
        super.onCreateOptionsMenu(menu);
        getMenuInflater().inflate(R.menu.menu_main, menu);

        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        Fragment menuFragment= null;
        JSONObject props = new JSONObject();
        Bundle args = new Bundle();
        String id = userData.getString("id",null);
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        getSupportActionBar().setDisplayShowCustomEnabled(true);
        switch (item.getItemId()) {
            case R.id.action_settings:
                android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
                android.webkit.CookieSyncManager.createInstance(this);
                cookieManager.removeAllCookie();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    props.put("Screen", "Signing Out");
                    mixpanel.track("Signing Out", props);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                try{
                    if (mGoogleApiClient.isConnected()) {
                        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                        mGoogleApiClient.disconnect();
                        mGoogleApiClient.connect();
                        userDataEditor.clear().commit();
                        inviteDataEditor.clear().commit();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                    else if(Session.getActiveSession() != null){
                        Session.getActiveSession().closeAndClearTokenInformation();
                        Session.setActiveSession(null);
                        userDataEditor.clear().commit();
                        inviteDataEditor.clear().commit();
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                    else{
                        if(!mGoogleApiClient.isConnected() || Session.getActiveSession()==null){
                            userDataEditor.clear().commit();
                            inviteDataEditor.clear().commit();
                            startActivity(new Intent(MainActivity.this, LoginActivity.class));
                        }

                        /*Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
                        mGoogleApiClient.disconnect();
                        mGoogleApiClient.connect();*/
                        //userDataEditor.clear().commit();
                    }
                /*if(type1.equalsIgnoreCase("facebook")) {
                    Log.d("fblogout","logout");
                    if (Session.getActiveSession() != null) {
                        Session.getActiveSession().closeAndClearTokenInformation();

                    }
                    Session.setActiveSession(null);
                    userDataEditor.remove("id");
                    userDataEditor.remove("type");
                    userDataEditor.remove("email");
                    userDataEditor.commit();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
                else{
                    signOutFromGplus();
                    if(glogout==true){
                        startActivity(new Intent(MainActivity.this, LoginActivity.class));
                    }
                }*/
                }catch (Exception e){
                    Log.d("Exception ","Exception");
                   /* if (Session.getActiveSession() != null) {
                        Session.getActiveSession().closeAndClearTokenInformation();
                    }else{
                        signOutFromGplus();
                    }*/
                    userDataEditor.clear().commit();
                    startActivity(new Intent(MainActivity.this, LoginActivity.class));
                }
                return true;

            case R.id.my_wallet:
                titleVisible=3;
                getSupportActionBar().setCustomView(R.layout.actionbarmywallet);
                try {
                    mixpanel.identify(userData.getString("id",null));
                    props.put("Screen", "My Wallet");
                    mixpanel.track("My Wallet", props);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                MyWallet myWallet= new MyWallet();
                this.getFragmentManager().beginTransaction()
                        .replace(R.id.frame_container, myWallet,"Mike")
                        .addToBackStack(null)
                        .commit();
                return true;
            case R.id.pending_cashback:
                titleVisible=5;
                getSupportActionBar().setCustomView(R.layout.actionbarpendingcashback);
                try {
                    mixpanel.identify(userData.getString("id",null));
                    props.put("Screen", "Cashback Status");
                    mixpanel.track("Cashback Status", props);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                PendingCashback pendingCashback= new PendingCashback();
                this.getFragmentManager().beginTransaction()
                        .replace(R.id.frame_container, pendingCashback,"Mike")
                        .addToBackStack(null)
                        .commit();
                return true;
            case R.id.my_favorites:
                titleVisible=1;
                getSupportActionBar().setCustomView(R.layout.actionbarmyfavorites);
                try {
                    mixpanel.identify(userData.getString("id",null));
                    props.put("Screen", "My Favorites");
                    mixpanel.track("My Favorites", props);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                args.putString("key", apiData.getString("myfavourite.url",null)+"?user_id="+id);
                DealsHomeFragment favoritesFragment= new DealsHomeFragment();
                this.getFragmentManager().beginTransaction()
                        .replace(R.id.frame_container, favoritesFragment,"Mike")
                        .addToBackStack(null)
                        .commit();
                favoritesFragment.setArguments(args);
                return true;
            case R.id.my_profile:
                titleVisible=6;
                getSupportActionBar().setCustomView(R.layout.actionbarmyprofile);
                try {
                    mixpanel.identify(userData.getString("id",null));
                    props.put("Screen", "My Profile");
                    mixpanel.track("My profile", props);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                MyProfile myProfile= new MyProfile();
                this.getFragmentManager().beginTransaction()
                        .replace(R.id.frame_container, myProfile,"Mike")
                        .addToBackStack(null)
                        .commit();
                return true;
            case R.id.my_order:
                titleVisible=4;
                getSupportActionBar().setCustomView(R.layout.actionbarmyorders);
                try {
                    mixpanel.identify(userData.getString("id",null));
                    props.put("Screen", "My Orders");
                    mixpanel.track("My Orders", props);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                args.putString("key", apiData.getString("myorders.url",null)+"?user_id="+id);
                DealsHomeFragment orderFragment= new DealsHomeFragment();
                this.getFragmentManager().beginTransaction()
                        .replace(R.id.frame_container, orderFragment,"Mike")
                        .addToBackStack(null)
                        .commit();
                orderFragment.setArguments(args);

                return true;
            case R.id.my_preferences:
                titleVisible=2;
                getSupportActionBar().setCustomView(R.layout.actionbarprefernces);
                try {
                    mixpanel.identify(userData.getString("id",null));
                    props.put("Screen", "My Preferences");
                    mixpanel.track("My Preferences", props);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                PreferencesFragment my_preferences = new PreferencesFragment();
                this.getFragmentManager().beginTransaction()
                        .replace(R.id.frame_container, my_preferences,"Mike")
                        .addToBackStack(null)
                        .commit();

                return true;
           default:
                return super.onOptionsItemSelected(item);
        }


    }
    public void signOutFromGplus() {


        if (mGoogleApiClient.isConnected()) {
            Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
            mGoogleApiClient.disconnect();
            mGoogleApiClient.connect();
            glogout=true;
            userDataEditor.remove("id");
            userDataEditor.remove("type");
            userDataEditor.remove("email");
            userDataEditor.commit();
        } else {
            glogout=false;
            }
    }

    @Override
    public void onConnected(Bundle bundle) {

    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {

    }

    @Override
    public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
        Toast.makeText(getApplicationContext(),"Toast in saved instance" + flag,Toast.LENGTH_SHORT).show();
        super.onSaveInstanceState(outState, outPersistentState);
    }
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
 Intent i= new Intent(MainActivity.this,MainActivity.class);
        i.putExtra("displayView","0");
        startActivity(i);
    }

    @Override
    public boolean onMenuOpened(int featureId, Menu menu)
    {
        if(featureId == Window.FEATURE_ACTION_BAR && menu != null){
            if(menu.getClass().getSimpleName().equals("MenuBuilder")){
                try{
                    Method m = menu.getClass().getDeclaredMethod(
                            "setOptionalIconsVisible", Boolean.TYPE);
                    m.setAccessible(true);
                    m.invoke(menu, true);

                }
                catch(Exception e){
                    throw new RuntimeException(e);
                }
            }
        }
        return super.onMenuOpened(featureId, menu);
    }

    private void displayView(int position) {
        titleVisible=0;
        Bundle args = new Bundle();
        Tracker t = ((GoogleAnalyticsTracker) getApplicationContext()).getTracker(
                GoogleAnalyticsTracker.TrackerName.APP_TRACKER);
        String id = userData.getString("id",null);
        Fragment fragment = null;
        switch (position) {
            case 0:
                JSONObject props = new JSONObject();
                try {
                    mixpanel.getPeople().set( "$last_login",new Date());
                    mixpanel.identify(userData.getString("id",null));
                    props.put("Screen", "Deals Screen");
                    mixpanel.track("Deals", props);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("Deals ")
                        .setLabel("Deals Clicked")
                        .build());
                args.putString("key", apiData.getString("mobile.website.url","")+"?user_id="+id);
                fragment = new DealsHomeFragment();
                fragment.setArguments(args);
                break;
            case 1:
                JSONObject props1 = new JSONObject();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    props1.put("Screen", "Search");
                    mixpanel.track("Search", props1);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("Search ")
                        .setLabel("Search Clicked")
                        .build());
                args.putString("key", apiData.getString("search.url",null)+"?user_id="+id);
                fragment = new DealsHomeFragment();
                fragment.setArguments(args);
                break;
            case 2:
                JSONObject propsAmazon = new JSONObject();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    propsAmazon.put("Screen", "Amazon");
                    mixpanel.track("Amazon", propsAmazon);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("Amazon ")
                        .setLabel("Amazon Clicked")
                        .build());
                args.putString("key", apiData.getString("affiliate.url.redirect","")+"?user_id="+userData.getString("id","")+"&store_id="+apiData.getString("store.code.amazon",""));
                fragment = new DealsHomeFragment();
                fragment.setArguments(args);
                break;
            case 3:
                JSONObject propsFlipkart = new JSONObject();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    propsFlipkart.put("Screen", "Flipkart");
                    mixpanel.track("Flipkart", propsFlipkart);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("Flipkart ")
                        .setLabel("Flipkart Clicked")
                        .build());
                args.putString("key", apiData.getString("affiliate.url.redirect","")+"?user_id="+userData.getString("id","")+"&store_id="+apiData.getString("store.code.flipkart",""));
                fragment = new DealsHomeFragment();
                fragment.setArguments(args);
                break;
            case 4:
                JSONObject propsSaholic = new JSONObject();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    propsSaholic.put("Screen", "Saholic");
                    mixpanel.track("Saholic", propsSaholic);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("Saholic ")
                        .setLabel("Saholic Clicked")
                        .build());
                args.putString("key", apiData.getString("saholic.autologin.url","")+"?user_id="+userData.getString("id",""));
                fragment = new DealsHomeFragment();
                fragment.setArguments(args);
                break;
            case 5:
                JSONObject propsSnapdeal = new JSONObject();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    propsSnapdeal.put("Screen", "Snapdeal");
                    mixpanel.track("Snapdeal", propsSnapdeal);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("Snapdeal ")
                        .setLabel("Snapdeal Clicked")
                        .build());
                args.putString("key", apiData.getString("affiliate.url.redirect","")+"?user_id="+userData.getString("id","")+"&store_id="+apiData.getString("store.code.snapdeal",""));
                fragment = new DealsHomeFragment();
                fragment.setArguments(args);
                break;
            case 6:
                JSONObject propsContactUs = new JSONObject();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    propsContactUs.put("Screen", "Contact Us");
                    mixpanel.track("Contact Us", propsContactUs);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("Contact Us ")
                        .setLabel("Contact us Clicked")
                        .build());
                fragment = new ContactUsFragment();
                break;
            case 7:
                JSONObject propsHowItWorks = new JSONObject();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    propsHowItWorks.put("Screen", "How it Works");
                    mixpanel.track("How it Works", propsHowItWorks);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("Tutorials ")
                        .setLabel("Tutorials Clicked")
                        .build());
                fragment = new HowItWorksFragment();
                break;
            case 8:
                JSONObject propsAboutUs = new JSONObject();
                try {
                    mixpanel.identify(userData.getString("id",null));
                    propsAboutUs.put("Screen", "About Us");
                    mixpanel.track("About Us", propsAboutUs);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                t.send(new HitBuilders.EventBuilder()
                        .setCategory("Menu")
                        .setAction("About Us ")
                        .setLabel("About us Clicked")
                        .build());
                fragment = new AboutUsFragment();
                break;
            default:
                break;
        }
        if (fragment != null) {
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction().replace(R.id.frame_container, fragment).commit();
            mDrawerList.setItemChecked(position, true);
            mDrawerList.setSelection(position);
            setTitle(navMenuTitles[position]);
            mDrawerLayout.closeDrawer(mDrawerList);
        } else {
            Log.e("MainActivity", "Error in creating fragment");
        }
    }



    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        mDrawerToggle.syncState();
    }

    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        boolean drawerOpen = shouldGoInvisible;
        hideMenuItems(menu, !drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }
    private void hideMenuItems(Menu menu, boolean visible)
    {
       for(int i = 0; i < menu.size(); i++){
        menu.getItem(i).setVisible(visible);
       }
    }
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        mDrawerToggle.onConfigurationChanged(newConfig);
    }
    @Override
    public boolean onKeyUp(int keycode, KeyEvent e) {
        switch(keycode) {
            case KeyEvent.KEYCODE_MENU:

                if (mainMenu !=null) {
                    mainMenu.performIdentifierAction(R.id.overflowMenu,0);
                }
        }

        return super.onKeyUp(keycode, e);
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        switch(keyCode) {
            case KeyEvent.KEYCODE_MENU:
                  if (mainMenu !=null) {
                  mainMenu.performIdentifierAction(R.id.overflowMenu,0);
                  }
        }
        return super.onKeyUp(keyCode, event);
    }
    private Menu mainMenu;
    public final boolean isInternetOn() {

        ConnectivityManager connec =
                (ConnectivityManager)getSystemService(this.getBaseContext().CONNECTIVITY_SERVICE);

        if ( connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTED ||
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTING ||
                connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.CONNECTED ) {

            Toast.makeText(this, " Connected ", Toast.LENGTH_LONG).show();
            return true;

        } else if (
                connec.getNetworkInfo(0).getState() == android.net.NetworkInfo.State.DISCONNECTED ||
                        connec.getNetworkInfo(1).getState() == android.net.NetworkInfo.State.DISCONNECTED  ) {

            Toast.makeText(this, " Not Connected ", Toast.LENGTH_LONG).show();
            return false;
        }
        return false;
    }
    class NotificationOpenedData extends AsyncTask<ArrayList<NameValuePair>, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();

        }

        @Override
        protected String doInBackground(ArrayList<NameValuePair>... arg0) {

            try {
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(apiData.getString("notification.data.url","http://api.profittill.com/pushnotifications/add"));
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                httppost.setEntity(new UrlEncodedFormEntity(arg0[0]));
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity entity = response.getEntity();
                int status = response.getStatusLine().getStatusCode();

                if(status == 200){
                    Log.d("Notification Opened","Notication opened and main activity page and sent successfully");
                    Log.d("ResponseCode GCM ",status+"");
                } else {
                    Log.d("ResponseCode GCM ",status+"");
                }

                nameValuePairsGcm.clear();
                Log.e("pass 1", "connection success ");
            } catch (Exception e) {
                Log.e("Fail 1", e.toString());

            }
            return "success";
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            Log.d("Notification Opened","Notication opened and main activity page");
        }
    }
}