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.util.Log;
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.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 RecentFragment extends TrackingListFragment {



    protected boolean isActive()
    {
        return ApexTrackingApplication.getInstance().homeactive&&ApexTrackingApplication.getInstance().recentactive;
    }

    public RecentFragment() {
        // Required empty public constructor
    }

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

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

        // this.getListView().setBackgroundColor(Color.WHITE);
//
//        if (savedInstanceState != null) {
//            String jsonString = savedInstanceState.getString("RecentJson");
//            if (jsonString != null) {
//                try {
//                    JSONObject json = new JSONObject(jsonString);
//                    handleJson(json);
//                } catch (JSONException e) {
//                    e.printStackTrace();
//                }
//            }
//        }

        if (searchresult.get_count() == 0) {
            requestData();
        }

    }

//    @Override
//    protected void requestData() {
//
//        requestdata();
//    }
//    @Override
//<<<<<<< .mine
//    protected void requestData()
//=======
//    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
//        return super.onCreateView(inflater, container, savedInstanceState);
//    }
//
//    @Override
//    public void onSaveInstanceState(Bundle outState) {
//        super.onSaveInstanceState(outState);
//        if (mJson != null) {
//            outState.putString("RecentJson",mJson.toString());
//        }
//    }
//
//    @Override
//    protected void requestData() {
//
//        requestdata();
//    }

    private void handleJson(JSONObject jsobj) {

        mJson = jsobj;
        if (mJson == null) {
            return;
        }
        try {
            int result = jsobj.getInt("result");
            if (result == Network.RESULT_TRUE) {

                searchresult.clear();
                JSONArray datalist = jsobj.getJSONArray("container_list");
                int count = datalist.length();
                searchresult.add_records(datalist.toString(), count);

                adapter.notifyDataSetChanged();
            } else {
                String msg = jsobj.getString("err_msg");
                showAlert(msg);
            }
        } catch (JSONException e) {
            e.printStackTrace();
            showAlert("Sorry,there is some wrong");
        }
    }
@Override
    protected void requestData()

    {
        if (isLoading) {
            if (mSwipeRefresh.isRefreshing()) {
                mSwipeRefresh.setRefreshing(false);
            }
            return;
        }
        isLoading = true;
//        showProgress(true);
        showProgressDialog();

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

                final JSONObject jsobj = Network.request_home();

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

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

                        dismissProgressDialog();

                        if (jsobj != null) {
                            handleJson(jsobj);
                            bdirty = false;
                        } else {
                            showAlert("Sorry,there is some wrong");
                        }
                        isLoading = false;
                    }
                });
            }
        }).start();

//
//        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();


        super.requestData();
    }

    @Override
    protected View initHeaderView()
    {

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

    }

    @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);

    }


    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);

        Log.d("RecentFragment", "onSaveInstanceState: ");
    }
}
