Vedroid36
4/16/2014 - 1:37 PM

gistfile1.java

package com.Klitch.Sprints.activities;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.Loader;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.Klitch.Sprints.R;
import com.Klitch.Sprints.adapters.WaitHelpAdapter;
import com.Klitch.Sprints.api.ApiRequestAsyncLoader;
import com.Klitch.Sprints.fragments.OfferHelpDialogFragment;
import com.Klitch.Sprints.helpers.Utils;
import com.Klitch.Sprints.holders.MyCommunityHolder;
import com.Klitch.Sprints.holders.WaitHelpHolder;
import com.google.gson.Gson;
import com.markupartist.android.widget.PullToRefreshListView;
import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;

/**
 * Created by Aleks on 23.02.14.
 */
public class WaitHelpActivity extends ActionBarActivity implements LoaderManager.LoaderCallbacks<String>, View.OnClickListener,
        AdapterView.OnItemClickListener, PullToRefreshListView.OnRefreshListener {

/*

1.  PUT /outbound/requests   (Create Klitch)
1.  POST /outbound/requests   (change Klitch status)  ->  cancelled, finished

2. PUT /outbound/offers


*/
    public static final String LOG_TAG = "WaitHelpActivity";
    public final static String BROADCAST_UPDATE_WAITHELP_LIST = "com.Klitch.Sprints.broadcast.update.waithelp.list";

    public static final int LOADER_WAIT_HELP_LIST = 1;
    private final int SHOW_OFFER_HELP_DIALOG = 3;  // here value was 1, but LOADER_WAIT_HELP_LIST also 1, what's the point ??
    private final int HIDE_OFFER_HELP_DIALOG = 2;
    private final int TIME_INTERVAL = 15000;//15000;    // Milli seconds

    public View actBarView;
    public MyCommunityHolder com_data;

    private PullToRefreshListView wait_help_lv;
    private ArrayList<WaitHelpHolder> waitHelpList;
    private String flag_dialog;
    private Boolean show_dialog = true;
    private ProgressBar progress_bar;
    private Handler handler;
    private Thread thread_check_list;
    private ApiRequestAsyncLoader loader;

    private Integer clicked_position;
    private static WaitHelpHolder clicked_item = null;
    private static WaitHelpHolder previousClickedItem = null;

    private boolean isAlreadyClickedThisId = false;
    private String klitchStatusBeforeUpdate = "";
    private Integer selectedKlitchId = null;

    private BroadcastReceiver registerBroadcastUpdatelist;



    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d(LOG_TAG, "onCreate");

        setContentView(R.layout.activity_wait_help);

        com_data = new Gson().fromJson(getIntent().getStringExtra("com_data"), MyCommunityHolder.class);

        if (com_data != null) {
            createActionBar();
            setContent();
            registerBroadcastUpdatelist();
            // registerBroadcastCheckOffer();
        }
    }

    private void createActionBar() {
        ActionBar mActionBar = getSupportActionBar();
        mActionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
        actBarView = getLayoutInflater().inflate(R.layout.cust_act_bar_backbtn, null);
        ((TextView) actBarView.findViewById(R.id.title)).setText(com_data.getName());
        progress_bar = (ProgressBar) actBarView.findViewById(R.id.progress_bar);
        actBarView.findViewById(R.id.leftImg).setOnClickListener(this);
        mActionBar.setCustomView(actBarView);
    }

    private void setContent() {
        Log.i(LOG_TAG, "setContent");

        wait_help_lv = (PullToRefreshListView) findViewById(R.id.wait_help_lv);

        progress_bar.setVisibility(View.VISIBLE);
        wait_help_lv.setOnItemClickListener(this);
        wait_help_lv.setOnRefreshListener(this);
        findViewById(R.id.btn_map).setOnClickListener(this);
        setCyclicCheckList();
    }

    private void loadWaitHelpList() {
        if (getSupportLoaderManager().getLoader(LOADER_WAIT_HELP_LIST) == null) {
            getSupportLoaderManager().initLoader(LOADER_WAIT_HELP_LIST, null, this).forceLoad();
        } else {
            getSupportLoaderManager().restartLoader(LOADER_WAIT_HELP_LIST, null, this).forceLoad();
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.leftImg:
                finish();
                break;
            case R.id.btn_map:
                if (com_data != null) {
                    String data = new Gson().toJson(com_data);
                    Intent intent = new Intent(this, MapActivity.class);
                    intent.putExtra("flag", "waiting");
                    intent.putExtra("com_data", data);
                    startActivity(intent);
                }
                break;
        }
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        clicked_position = (position - 1);
        Log.i(LOG_TAG, "onItemClick: " + new Gson().toJson(waitHelpList.get(clicked_position)));

        clicked_item = waitHelpList.get(clicked_position);
        if (clicked_item == null) return;

        selectedKlitchId = clicked_item.getRequestId();

        Integer oldOfferId = null;
        if (previousClickedItem != null) {
            oldOfferId = previousClickedItem.getRequestId();
        }

        Log.d(LOG_TAG, "clicked_item ID:  " + clicked_item);
        Log.d(LOG_TAG, "oldOfferId ID:  " + oldOfferId);


        if ( (oldOfferId != null) && (oldOfferId == clicked_item.getRequestId()) ) {
            isAlreadyClickedThisId = true;
        } else {
            isAlreadyClickedThisId = false;
        }

        Log.d(LOG_TAG, "isAlreadyClickedThisId:  " + isAlreadyClickedThisId);


        // iF user already made any offer -> show Dialog with Button "Cancel Offer"

        if ( (clicked_item.getOfferMade() != null) && (clicked_item.getOfferMade() != "null") ) {

            Log.d(LOG_TAG, "getOfferMade: " + clicked_item.getOfferMade() + " > startOfferHelpDialogFragment");
            //Toast.makeText(this, "Вы уже предложили помощь для этого клича", Toast.LENGTH_SHORT).show();
            startOfferHelpDialogFragment();
            return;
        }


        if (clicked_item.getStatus().equals("finished")) {
            Toast.makeText(this, "Этот клич уже завершен", Toast.LENGTH_SHORT).show();
            return;
        } else if (clicked_item.getStatus().equals("cancelled")) {
            Toast.makeText(this, "Этот клич был отменен", Toast.LENGTH_SHORT).show();
            return;
        } else {
            Toast.makeText(this, "Этот клич активен", Toast.LENGTH_SHORT).show();
        }

        if ( (clicked_item.getStatus().equals("ready") == true) || (isAlreadyClickedThisId == false) ) {
            startOfferHelpDialogFragment();
        }
    }


    @Override
    public void onLoaderReset(Loader<String> stringLoader) {

    }


    @Override
    public Loader onCreateLoader(int loader_id, Bundle bundle) {
        Log.i(LOG_TAG, "onCreateLoader: " + loader_id);

        progress_bar.setVisibility(View.VISIBLE);

        if (LOADER_WAIT_HELP_LIST == loader_id) {
            Log.d(LOG_TAG, "LOADER_WAIT_HELP_LIST");

            Log.d(LOG_TAG, "STATUS BEFORE UPDATE:  " + klitchStatusBeforeUpdate);

            if ((clicked_item != null) &&  (clicked_item.getStatus() != null )) {

                //Log.d(LOG_TAG, "clicked_item. STATUS:  " + clicked_item.getStatus());
                //klitchStatusBeforeUpdate = clicked_item.getStatus();

            } else {
                Log.d(LOG_TAG, "clicked_item is NULL or status is NULL!");
            }

            Log.d(LOG_TAG, "request string: " + "current/inbound/requests/" + com_data.getComId() + "get");


            loader = new ApiRequestAsyncLoader(this, "current/inbound/requests/" + com_data.getComId(), "", "get");
        }
        return loader;
    }


    @Override
    public void onLoadFinished(Loader<String> stringLoader, String response) {
        Log.i(LOG_TAG, "onLoadFinished,  ID:  " + stringLoader.getId() + "\n response" + response);

        if (Utils.checkResponse(this, response) == true) {
            if (LOADER_WAIT_HELP_LIST == stringLoader.getId()) {
                createList(response);
            }
        }
        wait_help_lv.onRefreshComplete();
        progress_bar.setVisibility(View.INVISIBLE);
    }


    private void createList(String response) {
        Log.d(LOG_TAG, "createList: " + response);

        Boolean showOfferDialog = false;
        Boolean klitch_finished = false;

        waitHelpList = new ArrayList<>();

        try {
            JSONArray json_array = new JSONArray(response);
            if (json_array.length() == 0) {
                Toast.makeText(this, "Список ждущих помощи пуст", Toast.LENGTH_SHORT).show();
                handler_dialog.sendEmptyMessage(HIDE_OFFER_HELP_DIALOG);
            }

            for (int i = 0; i < json_array.length(); i++) {

                WaitHelpHolder waitHelpHolder = new WaitHelpHolder();
                waitHelpHolder.setUserId(json_array.getJSONObject(i).getInt("user_id"));
                waitHelpHolder.setRequestId(json_array.getJSONObject(i).getInt("request_id"));
                waitHelpHolder.setStatus(json_array.getJSONObject(i).getString("status"));

                Log.d(LOG_TAG, "clicked_item ID:  :  " + selectedKlitchId);
                Log.d(LOG_TAG, "CURRENT item ID::  " + waitHelpHolder.getRequestId());

                Log.d(LOG_TAG, "OLD STATUS:  " + klitchStatusBeforeUpdate);
                Log.d(LOG_TAG, "NEW STATUS:  " + klitchStatusBeforeUpdate);

                if (clicked_item == null) {
                    Log.d(LOG_TAG, "no klitch selected -> no status to check");

                } else if ( (clicked_item.getRequestId() == waitHelpHolder.getRequestId()) && (klitchStatusBeforeUpdate != waitHelpHolder.getStatus()) ) {
                    showOfferDialog = true;
                    klitchStatusBeforeUpdate =  waitHelpHolder.getStatus();
                }

                waitHelpHolder.setHasOffer(json_array.getJSONObject(i).getBoolean("has_offer"));
                waitHelpHolder.setWithPayment(json_array.getJSONObject(i).getBoolean("with_payment"));
                waitHelpHolder.setExpires(json_array.getJSONObject(i).getString("expires"));
                waitHelpHolder.setProblems(json_array.getJSONObject(i).getString("problems"));
                waitHelpHolder.setCommunityId(json_array.getJSONObject(i).getInt("community_id"));
                waitHelpHolder.setLat(json_array.getJSONObject(i).getDouble("latitude"));
                waitHelpHolder.setLng(json_array.getJSONObject(i).getDouble("longitude"));
                waitHelpHolder.setNick(json_array.getJSONObject(i).getString("nick"));
                waitHelpHolder.setOfferMade(json_array.getJSONObject(i).getString("offer_made"));
                waitHelpHolder.setPhone(json_array.getJSONObject(i).getString("phone"));
                waitHelpHolder.setFields(json_array.getJSONObject(i).getString("fields"));
                waitHelpHolder.setDistance(Math.round(Utils.getDistance(this, json_array.getJSONObject(i).getDouble("latitude"), json_array.getJSONObject(i).getDouble("longitude"))) / 1000);
                waitHelpList.add(waitHelpHolder);

                Log.i(LOG_TAG, "getIntent().hasExtra(request_id): " + getIntent().hasExtra("request_id"));
                Log.i(LOG_TAG, "waitHelpHolder.getStatus(): " + waitHelpHolder.getStatus());
                Log.i(LOG_TAG, "Waiting Help List -> clicked_item: " + clicked_item);

                // Popup from push
                if (getIntent().hasExtra("request_id") && getIntent().getStringExtra("request_id") != null) {
                    if ((json_array.getJSONObject(i).getInt("request_id") == Integer.parseInt(getIntent().getStringExtra("request_id")))) {
                        clicked_item = waitHelpHolder;
                        flag_dialog = getIntent().getStringExtra("flag_dialog");
                    }
                }


                if ((clicked_item != null) && ((clicked_item.getCommunityId() == waitHelpHolder.getCommunityId()))) {

                    if (waitHelpHolder.getStatus().equals("finished") == true) {

                        klitch_finished = true;
                        Log.d(LOG_TAG, "klitch_finished: " + klitch_finished);

                        if (json_array.getJSONObject(i).getString("offer_made") == null) {
                            Log.d(LOG_TAG, "offer_made:  NULL");
                        }
                        Log.d(LOG_TAG, "flag_dialog: " + flag_dialog  + "");
                    }
                }

            }
        } catch (JSONException e) {
            e.printStackTrace();
        }

        wait_help_lv.setAdapter(new WaitHelpAdapter(this, waitHelpList, wait_help_lv));
        progress_bar.setVisibility(View.INVISIBLE);


        if ((flag_dialog != null) && (flag_dialog.equals("startOfferHelpDialogFragment") == true) && (show_dialog == true)) {


            if (showOfferDialog == true) {
                handler_dialog.sendEmptyMessage(SHOW_OFFER_HELP_DIALOG);
            }


            if (klitch_finished == true) {
                show_dialog = false;
            }

        }
    }



    private Handler handler_dialog = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            Log.i(LOG_TAG, "handleMessage: " + msg);
            switch (msg.what) {
                case SHOW_OFFER_HELP_DIALOG:
                    startOfferHelpDialogFragment();
                    break;
                case HIDE_OFFER_HELP_DIALOG:
                    hideOfferHelpDialogFragment();
                    break;
            }

        }
    };

    private void startOfferHelpDialogFragment() {
        Log.d(LOG_TAG, "startOfferHelpDialogFragment");

        flag_dialog = null;
        getIntent().removeExtra("flag_dialog");

        // check is intent extra REALLY removed
        if ((getIntent() != null) && (getIntent().getBooleanExtra("flag_dialog", false) == true) ) {
            Log.d(LOG_TAG, " check is intent extra REALLY removed:  NO" + getIntent().getBooleanExtra("flag_dialog", false));
        } else {
            Log.d(LOG_TAG, " check is intent extra REALLY removed:  YES");
        }


        Log.d(LOG_TAG, "isAlreadyClickedThisId:  " + isAlreadyClickedThisId);
        Log.d(LOG_TAG, "clicked_item.getRequestId():  " + clicked_item.getRequestId());

        if (clicked_item == null) {
          return;
        }


        if ( (isAlreadyClickedThisId == true) && (clicked_item.getStatus().equals("ready") != true) ) {
            Log.d(LOG_TAG, "DO NOT SHOW OfferHelpDialog ");
            Log.d(LOG_TAG, "return from startOfferHelpDialogFragment");
            return;
        } else {
            Log.d(LOG_TAG, "clicked_item: " + clicked_item + " ->>  SHOW OfferHelpDialog ");
        }

        klitchStatusBeforeUpdate = clicked_item.getStatus();
        Log.d(LOG_TAG, "ITEM STATUS BEFORE DIALOG SHOWN: " + klitchStatusBeforeUpdate);

        Bundle bn = new Bundle();
        bn.putString("data", new Gson().toJson(clicked_item));
        bn.putString("flag", "WaitHelpActivity");

        hideOfferHelpDialogFragment();
        OfferHelpDialogFragment.newInstance(bn).show(getSupportFragmentManager(), "offerHelpDialogFragment");
    }


    private void hideOfferHelpDialogFragment() {
        Log.d(LOG_TAG, "hideOfferHelpDialogFragment");

        Fragment previousFragment = getSupportFragmentManager().findFragmentByTag("offerHelpDialogFragment");

        if ( (previousFragment != null) && (previousFragment.isVisible() == true) ) {
            ((OfferHelpDialogFragment) previousFragment).dismiss();
        }
    }

    /*
    *  Broadcast registerBroadcastUpdatelist will be called if HELP OFFER status was changed.
    *
    *  It could be 2 reasons:
    *      a) HELP OFFER was ACCEPTED (help offer was sent to server)
    *      b) HELP OFFER was cancelled (and also answer was sent to server)
    */
    private void registerBroadcastUpdatelist() {
        final String TAG = "WaitForHelp Act: Broadcast Updatelist";

         registerBroadcastUpdatelist = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.d(TAG, "onReceive");

                String strAction = intent.getAction();

                if (strAction == null) {
                    return;
                }

                if ((intent.hasExtra("flag_dialog") == true) && (intent.getStringExtra("flag_dialog") != null)) {
                    flag_dialog = intent.getStringExtra("flag_dialog");
                }

                if (strAction.equals(BROADCAST_UPDATE_WAITHELP_LIST) == true) {
                    if (getSupportLoaderManager().getLoader(LOADER_WAIT_HELP_LIST) == null) {
                        getSupportLoaderManager().initLoader(LOADER_WAIT_HELP_LIST, null, WaitHelpActivity.this).forceLoad();
                    } else {
                        getSupportLoaderManager().restartLoader(WaitHelpActivity.LOADER_WAIT_HELP_LIST, null, WaitHelpActivity.this).forceLoad();
                    }
                }
            }
        };

        registerReceiver(registerBroadcastUpdatelist, new IntentFilter(BROADCAST_UPDATE_WAITHELP_LIST));

    }

    private void setCyclicCheckList() {
        Log.i(LOG_TAG, "setCyclicCheckList");

        handler = new Handler();
        thread_check_list = new Thread() {
            @Override
            public void run() {
                loadWaitHelpList();
                handler.postDelayed(this, TIME_INTERVAL);
            }
        };
        handler.post(thread_check_list);
    }


    @Override
    public void onRefresh() {
        Log.i(LOG_TAG, "onRefresh ");
        loadWaitHelpList();
    }


    @Override
    public void onResume() {
        super.onResume();
        Log.i(LOG_TAG, "onResume ");

    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(LOG_TAG, "onStop ");
        previousClickedItem = clicked_item;
        clicked_item = null;

        Log.d(LOG_TAG, "previousClickedItem:  " + previousClickedItem);
        Log.d(LOG_TAG, "clicked_item:  " + clicked_item);
    }

}