Subversion Repositories SmartDukaan

Rev

Rev 16080 | Blame | Compare with Previous | Last modification | View Log | RSS feed

package com.saholic.profittill.main;

import android.app.Fragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.HttpAuthHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.mixpanel.android.mpmetrics.MixpanelAPI;
import com.saholic.profittill.Constants.ProfitTillConstants;
import com.saholic.profittill.R;
import com.saholic.profittill.Utils.AnalyticsUtility;
import com.saholic.profittill.Volley.Analytics;
import com.saholic.profittill.Volley.AnalyticsErrorResponse;
import com.saholic.profittill.Volley.AnalyticsJsonResponse;
import com.testin.agent.TestinAgent;

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

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

public class PreferencesFragment extends Fragment {
    WebView preferencesWebView;
    SharedPreferences userData;
    SharedPreferences apiData;
    SharedPreferences.Editor userDataEditor;
    SharedPreferences.Editor apiSettingsEditor;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_preferences, container, false);
        TestinAgent.init(getActivity());
        MixpanelAPI mixpanel = MixpanelAPI.getInstance(getActivity(), ProfitTillConstants.MIX_PANEL_TOKEN);
        userData = getActivity().getSharedPreferences("User_Data", Context.MODE_PRIVATE);
        apiData = getActivity().getSharedPreferences("API_Data", Context.MODE_PRIVATE);
        userDataEditor = userData.edit();
        apiSettingsEditor = apiData.edit();
        String url=apiData.getString("preferences.url", null);;
        String id = userData.getString("id", null);
        String  landingUrl;
        if(userData.getString("preferences","false").equalsIgnoreCase("true")) {
            landingUrl =url+"?user_id="+id+"&firsttime=1";
        }else {
            landingUrl=url+"?user_id="+id;
        }
        TestinAgent.setUserInfo(userData.getString("id", ""));
        JSONObject props = new JSONObject();
        try {
            mixpanel.identify(userData.getString("id",null));
            props.put("Screen", "My Preferences");
            mixpanel.track("My Preferences", props);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        if(isInternetOn()) {
            WebClientClass webViewClient = new WebClientClass();
            preferencesWebView  = (WebView)rootView.findViewById(R.id.preferencesWebView);
            preferencesWebView.setClickable(true);
            preferencesWebView.setFocusableInTouchMode(true);
            preferencesWebView.getSettings().setJavaScriptEnabled(true);
            preferencesWebView.getSettings().setBuiltInZoomControls(true);
            new Analytics(ProfitTillConstants.ANALYTICS_URL,
                    AnalyticsUtility.getAnalyticsRequest(getActivity(), userData.getString("id", ""), "Screen", "My Preferences", "My Preferences Screen"),
                    AnalyticsJsonResponse.getAnalyticsRequestInstance(),
                    AnalyticsErrorResponse.getAnalyitcsResponseInstance()).anlyticsRequest(getActivity());
            if(Uri.parse(landingUrl).getHost().equalsIgnoreCase(ProfitTillConstants.DOMAIN)) {
                CookieSyncManager.createInstance(getActivity());
                CookieManager cookieManager1 = CookieManager.getInstance();
                cookieManager1.setCookie(url, "token=" + userData.getString("token", ""));
                cookieManager1.setCookie(url, "walletAuthentication=true");
                cookieManager1.setCookie(url, "shopcluesActive=true");
            }
            preferencesWebView.loadUrl(landingUrl);
            preferencesWebView.setWebViewClient(webViewClient);
        }
        else{
            SearchFragment nextFrag= new SearchFragment();
            Bundle args = new Bundle();
            args.putString("finishingurl", landingUrl);
            args.putString("fragmentNumber", "12");
            nextFrag.setArguments(args);
            getActivity().getFragmentManager().beginTransaction()
                    .replace(R.id.frame_container, nextFrag)
                    .addToBackStack(null)
                    .commit();
        }

        return rootView;
    }

    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
    }

    JSONObject obj;
    public class WebClientClass extends WebViewClient {
        ProgressDialog pd = null;

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            if(url.equalsIgnoreCase("http://m.saholic.com")){
                pd = new ProgressDialog(getActivity());
                pd.setTitle("Please wait");
                pd.setMessage("Loading..");
                pd.show();
            }
            super.onPageStarted(view, url, favicon);
            obj = new JSONObject();

            try {
                JSONObject j = new JSONObject();
                JSONArray jsArray = new JSONArray();
                j.put("url",url);
                j.put("user_id",userData.getString("id",null));
                j.put("time", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
                jsArray.put(j);
                obj.put("pushdata",jsArray);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            new pushData().execute();
        }
        @Override
        public void onPageFinished(WebView view, String url) {
            if(url.equalsIgnoreCase("http://m.saholic.com")) {
                pd.dismiss();
            }

            view.setOnKeyListener(new View.OnKeyListener()
            {
                @Override
                public boolean onKey(View v, int keyCode, KeyEvent event)
                {
                    if(event.getAction() == KeyEvent.ACTION_DOWN)
                    {
                        WebView webView = (WebView) v;

                        switch(keyCode)
                        {
                            case KeyEvent.KEYCODE_BACK:
                                if(webView.canGoBack())
                                {
                                    webView.goBack();
                                    return true;
                                }
                                else{
                                    Intent i = new Intent(getActivity(),MainActivity.class);
                                    i.putExtra("displayView","0");
                                    startActivity(i);
                                }
                                break;
                        }
                    }

                    return false;
                }
            });
            super.onPageFinished(view, url);
        }
        @Override
        public void onReceivedHttpAuthRequest(WebView view,
                                              HttpAuthHandler handler, String host, String realm) {

            handler.proceed("dtr", "dtr18Feb2015");

        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            super.shouldOverrideUrlLoading(view, url);

            if(url.contains(apiData.getString("mobile.website.url",""))){
                new Analytics(ProfitTillConstants.ANALYTICS_URL,
                        AnalyticsUtility.getAnalyticsRequest(getActivity(), userData.getString("id", ""), "Clicks", "My Preferences", "Show my deals"),
                        AnalyticsJsonResponse.getAnalyticsRequestInstance(),
                        AnalyticsErrorResponse.getAnalyitcsResponseInstance()).anlyticsRequest(getActivity());
                Intent i = new Intent(getActivity(),MainActivity.class);
                i.putExtra("displayView","0");
                startActivity(i);
            }

            return false;
        }
    }
    @Override
    public void onResume() {
        super.onResume();
        getView().setFocusableInTouchMode(true);
        getView().requestFocus();
        getView().setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {

                if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                    Intent i = new Intent(getActivity(), MainActivity.class);
                    i.putExtra("displayView", "0");
                    startActivity(i);
                    return true;

                }
                return false;
            }
        });
    }

    class pushData extends AsyncTask<String, Integer, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Log.e("Push Service", "Pre execute");
        }

        @Override
        protected String doInBackground(String... arg0) {
            HttpClient httpclient = new DefaultHttpClient();
            try {
                ArrayList<NameValuePair> nameValuePairs = new ArrayList<>();
                nameValuePairs.add(new BasicNameValuePair("pushdata",obj.toString()));
                HttpPost httppost = new HttpPost(apiData.getString("url.push.api",null));
                httppost.setHeader("Authorization", ProfitTillConstants.BASIC_AUTH);
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                System.out.println(obj.toString());
                StringEntity se = new StringEntity(obj.toString());
                HttpResponse response = httpclient.execute(httppost);
                int status = response.getStatusLine().getStatusCode();

                if(status == 200){
                    System.out.println("ResponseCode of record: "+ status + " is " + status);
                    return "success";
                } else {
                    Log.d("ResponseCode",status+"");
                    System.out.println(" NOT Transfered");
                    return "failure";
                }

            } catch (ClientProtocolException e) {
                return "failure";
            } catch (IOException e) {
                return "failure";
            }
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
        }
    }

    public final boolean isInternetOn() {

        ConnectivityManager connec =
                (ConnectivityManager)getActivity().getSystemService(getActivity().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 ) {
            return true;

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

            return false;
        }
        return false;
    }
}