package com.usai.apex.mainframe;


import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ListView;

import com.usai.apex.ApexTrackingApplication;
import com.usai.apex.DetailActivity;
import com.usai.apex.R;
import com.usai.apex.Result.PullRefreshListView;
import com.usai.util.Network;
import com.usai.util.dbUtil;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;


/**
 * A simple {@link Fragment} subclass.
 */
public class HistoryFragment extends TrackingListFragment {

//
//    boolean bactive = false;
//    public  void setActive(boolean active){
//        bactive = active;
//
//    }


    protected boolean isActive()
    {
        return ApexTrackingApplication.getInstance().historyactive;
    }
    public HistoryFragment() {
        // Required empty public constructor
        bdirty = true;
    }


    @Override
    public void onActivityCreated(Bundle savedInstanceState)
    {
        super.onActivityCreated(savedInstanceState);

//        setupAdapter();
//        customize_style();

        refresh_footer = View.inflate(mContext, R.layout.refresh_footer, null);
        mPullRefreshListView.setRefreshFooter(refresh_footer);
        mPullRefreshListView.setOnRefreshListener(new PullRefreshListView.OnRefreshListener() {
            @Override
            public void onHeaderStateChange(int state, int offset) {

            }

            @Override
            public void onFooterStateChange(int state, int offset) {
                if (state == PullRefreshListView.REFRESHING) {
                    if (!isLoading) {
                        loadContent(2);
                    }
                }
            }

            @Override
            public void shouldPullDownToRefresh(boolean should) {

            }
        });

        // this.getListView().setBackgroundColor(Color.WHITE);
//        if (searchresult.get_count() == 0) {
//            requestData();
//        }

    }
//    private void requestdata()
//    {
//
//        loadContent(0);
//
////        JSONObject jsobj = loadfakecontent(R.raw.fake_container_list);
////        // if (searchresult.get_fieldscount() == 0)
////        // {
////        // JSONObject objfields = jsobj.getJSONObject("fields");
////        // if (objfields != null)
////        // searchresult.init_fields(objfields.toString());
////        // }
////
////
////        try {
////            JSONArray datalist = jsobj.getJSONArray("container_list");
////            int count = datalist.length();
////            searchresult.add_records(datalist.toString(), count);
////
////        } catch (JSONException e) {
////            e.printStackTrace();
////        }
////
//////        int count = jsobj.getInt("total");
//////
//////        if (count < limit)
//////            bfinish = true;
//////        JSONObject objrecords = jsobj.getJSONObject("records");
//////        if (objrecords != null)
//////            searchresult.add_records(objrecords.toString(), count);
//////        errorcode = Network.RESULT_TRUE;
////
////        adapter.notifyDataSetChanged();
//    }
    @Override
    protected View initHeaderView()
    {

        View headerView = LayoutInflater.from(getActivity()).inflate(R.layout.invisable_listheader, null);
        return headerView;

    }

    @Override
    protected void requestData() {

        loadContent(0);
//        super.requestData();
    }

    private static final int load_limit = 10;
    private void loadContent(final int option) {

        if (isLoading) {
            if (mSwipeRefresh.isRefreshing()) {
                mSwipeRefresh.setRefreshing(false);
            }
            return;
        }

        int offset = 0;
        switch (option) {
            case 0:
            case 1: {
                offset = 0;
            }
            break;
            case 2: {
                offset = searchresult.get_count();
            }
            break;
        }

        final Bundle params = new Bundle();
        params.putInt("offset",offset);
        params.putInt("limit",load_limit);

        isLoading = true;
//        showProgress(true);

        showProgressDialog();

        new Thread(new Runnable() {
            @Override
            public void run() {

                final JSONObject jsobj = Network.request_history(params);

                ((Activity)mContext).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                        mPullRefreshListView.completeRefresh();
                        showProgress(false);
                        if (mSwipeRefresh.isRefreshing()) {
                            mSwipeRefresh.setRefreshing(false);
                        }

                        dismissProgressDialog();

                        if (jsobj != null) {

                            try {
                                int result = jsobj.getInt("result");
                                if (result == Network.RESULT_TRUE) {

                                    JSONArray datalist = jsobj.getJSONArray("container_list");
                                    int count = datalist.length();

                                    switch (option) {
                                        case 0:
                                        case 1: {
                                            searchresult.clear();
                                        }
                                        break;
                                        case 2: {

                                        }
                                        break;
                                    }

                                    searchresult.add_records(datalist.toString(), count);

                                    adapter.notifyDataSetChanged();

                                    if (count < load_limit) {
                                        showAlert("No More Data");
                                    }

                                    if(option==0)
                                        bdirty = false;

                                } else {
                                    String msg = jsobj.getString("err_msg");
                                    showAlert(msg);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                                showAlert("Sorry,there is some wrong");
                            }

                        } else {
                            showAlert("Sorry,there is some wrong");
                        }
                        isLoading = false;
                    }
                });
            }
        }).start();

    }

    @Override
    public void onListItemClick(ListView l, View v, int position, long id) {

        //!!!!! listview 有header， position 需要-1


//        Log.d("FragmentList", "Item clicked: " + id);
//
//        String title = (String) getData(jsonobj).get(position - 1).get("title");

        position = position - 1;
        if (position < 0) {
            return;
        }

        String cargo_criterion = (String) searchresult.getData().get(position).get("hbol");
        String serial_no = (String) searchresult.getData().get(position).get("serial_no");
        if(TextUtils.isEmpty(serial_no))
            serial_no = "dumb";

        Intent intent = new Intent();
        intent.setClass(getContext(), DetailActivity.class);

        intent.putExtra("action0", "Tracking");
        intent.putExtra("function_name", "Cargo Tracking");

        intent.putExtra("cargo_criterion", cargo_criterion);
        intent.putExtra("actions_count", 1);
        intent.putExtra("_id", serial_no);

        intent.putExtra("criterion_type", 0);
        String h_field = "h_bol";

        dbUtil.savehistory(h_field, cargo_criterion);

        startActivity(intent);

    }

}
