package ai.pai.client.activity;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.android.common.executors.ThreadExecutor;
import ai.pai.client.utils.HttpPostTask;
import com.android.common.utils.JSONParseUtils;
import com.android.views.swiperefreshrecyclerview.DividerItemDecoration;
import com.android.views.swiperefreshrecyclerview.EndlessRecyclerOnScrollListener;
import com.android.views.swiperefreshrecyclerview.HeaderAndFooterRecyclerViewAdapter;
import com.android.views.swiperefreshrecyclerview.RecyclerViewUtils;

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

import java.util.ArrayList;
import java.util.HashMap;

import ai.pai.client.R;
import ai.pai.client.adapter.OrderListAdapter;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.beans.OrderItem;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.SystemUtils;
import ai.pai.client.utils.UrlContainer;

public class OrderListActivity extends BaseActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener{

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private OrderListAdapter orderAdapter;
    private HeaderAndFooterRecyclerViewAdapter groupAdapter;
    private View loadMoreView;

    private HttpPostTask fetchOrdersTask;
    private EndlessRecyclerOnScrollListener scrollListener;

    private ArrayList<OrderItem> orderList = new ArrayList<OrderItem>();

    private int left = Integer.MAX_VALUE;
    private static  final int num = 20;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_list);
        SystemUtils.setImmerseLayout(this,findViewById(R.id.title_layout));
        TextView title = (TextView)findViewById(R.id.title_bar_middle_txt);
        title.setText(R.string.slide_order_history);
        findViewById(R.id.title_bar_back_layout).setOnClickListener(this);
        findViewById(R.id.title_bar_option_layout).setVisibility(View.INVISIBLE);
        swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_refresh_layout_orders);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_orders);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST));
        orderAdapter = new OrderListAdapter(this, orderList);
        groupAdapter = new HeaderAndFooterRecyclerViewAdapter(orderAdapter);
        recyclerView.setAdapter(groupAdapter);
        loadMoreView = LayoutInflater.from(this).inflate(R.layout.view_load_more, recyclerView, false);
        RecyclerViewUtils.setFooterView(recyclerView,loadMoreView);
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setRefreshing(true);
        scrollListener = new EndlessRecyclerOnScrollListener() {
            @Override
            public void onLoadMore() {
                if(left > 0){
                    loadMoreView.setVisibility(View.VISIBLE);
                    doFetchOrdersTask();
                }else{
                    Toast.makeText(OrderListActivity.this,R.string.no_more_content,Toast.LENGTH_SHORT).show();
                }

            }
        };
        recyclerView.addOnScrollListener(scrollListener);
        doFetchOrdersTask();
        loadMoreView.setVisibility(View.INVISIBLE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_bar_back_layout:
                finish();
                break;
            default:
                break;
        }
    }

    private synchronized void doFetchOrdersTask(){
        if(fetchOrdersTask !=null && fetchOrdersTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        if(orderAdapter ==null){
            return;
        }
        final int page = orderAdapter.getOrderList().size() /num +1;
        HashMap<String,String> params = new HashMap<String,String>();
        String userId = Preferences.getInstance(this).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("user_id",userId);
        params.put("page",String.valueOf(page));
        params.put("num",String.valueOf(num));

        fetchOrdersTask = new HttpPostTask(this,params) {
            ArrayList<OrderItem> orderItems = new ArrayList<OrderItem>();

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                scrollListener.setLoading(true);
            }

            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        JSONObject info = json.getJSONObject("data");
                        JSONArray orderArray = info.getJSONArray("orders");
                        if(orderArray!=null && orderArray.length()>0){
                            for(int k = 0; k<orderArray.length();k++){
                                JSONObject order = orderArray.getJSONObject(k);
                                OrderItem orderItem = new OrderItem();
                                orderItem.body = JSONParseUtils.getJSONString(order.getString("body"));
                                orderItem.createTime = JSONParseUtils.getJSONString(order.getString("created_at"));
                                orderItem.orderId = JSONParseUtils.getJSONString(order.getString("order_id"));
                                orderItem.payTime =  JSONParseUtils.getJSONString(order.getString("paid_at"));
                                orderItem.fromUid = JSONParseUtils.getJSONString(order.getString("from_uid"));
                                orderItem.payStatus = order.getInt("pay_status");
                                orderItem.groupId = JSONParseUtils.getJSONString(order.getString("group_id"));
                                orderItem.totalFee = order.getInt("total_fee");
                                orderItem.toUid =JSONParseUtils.getJSONString(order.getString("to_uid"));
                                orderItem.photoItem = GroupPhotoItem.parseFromJSON(order.getJSONObject("group_photo_info"));
                                orderItems.add(orderItem);
                            }
                        }
                        left = info.getInt("left");
                        return true;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);
                swipeRefreshLayout.setRefreshing(false);
                scrollListener.setLoading(false);
                loadMoreView.setVisibility(View.GONE);
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                swipeRefreshLayout.setRefreshing(false);
                scrollListener.setLoading(false);
                loadMoreView.setVisibility(View.GONE);
                if(orderItems !=null && orderItems.size()>0){
                    orderAdapter.addOrderList(orderItems);
                }else{
                    Toast.makeText(context,R.string.no_orders_found_tip,Toast.LENGTH_SHORT).show();
                }
            }
        };
        fetchOrdersTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.ORDER_LIST_URL);
    }

    @Override
    public void onRefresh() {
        if(orderAdapter !=null){
            orderAdapter.clearOrderList();
            left = Integer.MAX_VALUE;
        }
        doFetchOrdersTask();
    }

}
