Vedroid36
4/16/2014 - 2:41 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 {
    public static final String LOG_TAG = "WaitHelpActivity";
    public View actBarView;
    private PullToRefreshListView wait_help_lv;
    private ArrayList<WaitHelpHolder> waitHelpList;
    public MyCommunityHolder com_data;
    private String flag_dialog;
    private Boolean show_dialog = true;
    private ProgressBar progress_bar;
    private Handler handler;
    private final int TIME_INTERVAL = 15000;
    private Thread thread_check_list;
    public final static String BROADCAST_UPDATE_WAITHELP_LIST = "com.Klitch.Sprints.broadcast.update.waithelp.list";
    private ApiRequestAsyncLoader loader;
    public static final int LOADER_WAIT_HELP_LIST = 1;

    private Integer clicked_position;
    private static WaitHelpHolder clicked_item = null;

    private final int SHOW_OFFER_HELP_DIALOG = 1;
    private final int HIDE_OFFER_HELP_DIALOG = 2;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        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;
        if (clicked_item.getStatus().equals("finished") || clicked_item.getStatus().equals("cancelled")) {
            Toast.makeText(this, "Этот клич уже не активный", Toast.LENGTH_SHORT).show();
            return;
        }
        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) {
            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: " + response);

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

    private void createList(String response) {
        Log.i(LOG_TAG, "createList: " + response);
        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 whh = new WaitHelpHolder();
                whh.setUserId(json_array.getJSONObject(i).getInt("user_id"));
                whh.setStatus(json_array.getJSONObject(i).getString("status"));
                whh.setHasOffer(json_array.getJSONObject(i).getBoolean("has_offer"));
                whh.setWithPayment(json_array.getJSONObject(i).getBoolean("with_payment"));
                whh.setExpires(json_array.getJSONObject(i).getString("expires"));
                whh.setProblems(json_array.getJSONObject(i).getString("problems"));
                whh.setCommunityId(json_array.getJSONObject(i).getInt("community_id"));
                whh.setLat(json_array.getJSONObject(i).getDouble("latitude"));
                whh.setLng(json_array.getJSONObject(i).getDouble("longitude"));
                whh.setNick(json_array.getJSONObject(i).getString("nick"));
                whh.setRequestId(json_array.getJSONObject(i).getInt("request_id"));
                whh.setOfferMade(json_array.getJSONObject(i).getString("offer_made"));
                whh.setPhone(json_array.getJSONObject(i).getString("phone"));
                whh.setFields(json_array.getJSONObject(i).getString("fields"));
                whh.setDistance(Math.round(Utils.getDistance(this, json_array.getJSONObject(i).getDouble("latitude"), json_array.getJSONObject(i).getDouble("longitude"))) / 1000);
                waitHelpList.add(whh);

                Log.i(LOG_TAG, "getIntent().hasExtra(\"request_id\"): " + getIntent().hasExtra("request_id"));

                Log.i(LOG_TAG, "whh.getStatus(): " + whh.getStatus());

                Log.i(LOG_TAG, "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 = whh;
                        flag_dialog = getIntent().getStringExtra("flag_dialog");
                    }
                }

                // Popup if Klitch finished
                if(clicked_item != null && (clicked_item.getCommunityId() == whh.getCommunityId())){
                    if(whh.getStatus().equals("finished")){
                        klitch_finished = true;
                        flag_dialog = "startOfferHelpDialogFragment";
                    }
                }

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

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

        Log.i(LOG_TAG, "clicked_item: " + clicked_item);
        Log.i(LOG_TAG, "flag_dialog: " + flag_dialog);

        if (flag_dialog != null && flag_dialog.equals("startOfferHelpDialogFragment") && show_dialog) {
            handler_dialog.sendEmptyMessage(SHOW_OFFER_HELP_DIALOG);
            if (klitch_finished) {
                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() {
        // Reset flag_dialog
        flag_dialog = null;
        getIntent().removeExtra("flag_dialog");

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

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

    private void hideOfferHelpDialogFragment() {
        Fragment prev = getSupportFragmentManager().findFragmentByTag("offerHelpDialogFragment");
        if (prev != null && prev.isVisible()) {
            ((OfferHelpDialogFragment) prev).dismiss();
        }
    }

    private void registerBroadcastUpdatelist() {

        BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Log.i(LOG_TAG, "onReceive");

                String strAction = intent.getAction();
                if (strAction == null) {
                    return;
                }
                if (intent.hasExtra("flag_dialog") && intent.getStringExtra("flag_dialog") != null) {
                    flag_dialog = intent.getStringExtra("flag_dialog");
                }


                if (strAction.equals(BROADCAST_UPDATE_WAITHELP_LIST)) {
                    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(broadcastReceiver, 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 ");
        clicked_item = null;
    }
}