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 com.android.common.utils.JSONParseUtils;
import com.android.common.utils.LogHelper;
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.HistoryGroupAdapter;
import ai.pai.client.beans.GroupInfo;
import ai.pai.client.db.DBService;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.SystemUtils;
import ai.pai.client.utils.UrlContainer;

public class GroupListActivity extends BaseActivity implements View.OnClickListener,SwipeRefreshLayout.OnRefreshListener, HistoryGroupAdapter.GroupActionListener {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private HistoryGroupAdapter refreshAdapter;
    private HeaderAndFooterRecyclerViewAdapter groupAdapter;
    private View loadMoreView;
    private EndlessRecyclerOnScrollListener scrollListener;
    private HttpPostTask fetchGroupsTask;
    private ArrayList<GroupInfo> groupList = new ArrayList<GroupInfo>();

    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_my_groups);
        SystemUtils.setImmerseLayout(this,findViewById(R.id.title_layout));
        TextView title = (TextView)findViewById(R.id.title_bar_middle_txt);
        title.setText(R.string.slide_my_photo_group);
        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_groups);
        swipeRefreshLayout.setColorSchemeResources(R.color.colorPrimary);
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view_groups);
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration(this,DividerItemDecoration.VERTICAL_LIST));
        refreshAdapter = new HistoryGroupAdapter(this, groupList);
        refreshAdapter.addGroupActionListener(this);
        groupAdapter = new HeaderAndFooterRecyclerViewAdapter(refreshAdapter);
        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){
                    LogHelper.d(TAG,"group activity onLoadMore");
                    loadMoreView.setVisibility(View.VISIBLE);
                    doFetchGroupTask();
                }else{
                    Toast.makeText(GroupListActivity.this,R.string.no_more_content,Toast.LENGTH_SHORT).show();
                }

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

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

    private synchronized void doFetchGroupTask(){
        if(fetchGroupsTask!=null && fetchGroupsTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        if(refreshAdapter==null){
            return;
        }
        final int page = refreshAdapter.getGroupList().size() /num +1;
        LogHelper.d(TAG,"group activity doFetchGroupTask  start with page "+page);
        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));

        fetchGroupsTask = new HttpPostTask(this,params) {
            ArrayList<GroupInfo> groupItems = new ArrayList<GroupInfo>();

            @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 groupArray = info.getJSONArray("groups");
                        if(groupArray!=null && groupArray.length()>0){
                            for(int k = 0; k<groupArray.length();k++){
                                JSONObject group = groupArray.getJSONObject(k);
                                GroupInfo groupInfo = new GroupInfo();
                                groupInfo.groupId = JSONParseUtils.getJSONString(group.getString("group_id"));
                                groupInfo.groupName = JSONParseUtils.getJSONString(group.getString("group_name"));
                                groupInfo.createTime=JSONParseUtils.getJSONString(group.getString("created_at"));
                                groupInfo.desc = JSONParseUtils.getJSONString(group.getString("group_desc"));
                                groupInfo.groupFrom = group.getInt("group_from");
                                groupInfo.groupLock = group.getBoolean("group_lock");
                                groupInfo.groupAvatarId = group.getInt("group_default_avatar");
                                groupInfo.groupPhotoNum=group.getInt("group_photo_num");
                                groupInfo.adminId = group.getString("admin_id");
                                groupItems.add(groupInfo);
                            }
                        }
                        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);
                if(page==1){
                    groupItems = DBService.getInstance(context).getHistoryGroupList();
                    refreshAdapter.addGroupList(groupItems);
                }
            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);
                swipeRefreshLayout.setRefreshing(false);
                scrollListener.setLoading(false);
                loadMoreView.setVisibility(View.GONE);
                if(groupItems !=null && groupItems.size()>0){
                    LogHelper.d(TAG, "group activity   has new group and update adapter :"+ groupItems.size());
                    refreshAdapter.addGroupList(groupItems);
                    if(page==1){
                        DBService.getInstance(context).clearHistoryList();
                    }
                    DBService.getInstance(context).addHistoryList(groupItems);
                }else{
                    if(refreshAdapter.getItemCount()==0){
                        Toast.makeText(context,R.string.no_history_group_tip,Toast.LENGTH_SHORT).show();
                    }
                }
            }
        };
        fetchGroupsTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.HISTORY_GROUP_URL);
    }

    @Override
    public void onRefresh() {
        LogHelper.d(TAG,"group activity onRefresh");
        if(refreshAdapter!=null){
            refreshAdapter.clearGroupList();
            left = Integer.MAX_VALUE;
        }
        doFetchGroupTask();
    }

    @Override
    public void onGroupDeleted(GroupInfo groupInfo) {
        HashMap<String,String> params = new HashMap<String,String>();
        String userId = Preferences.getInstance(this).getUserId();
        if(userId.length()==0){
            return;
        }
        params.put("admin_id",userId);
        params.put("group_id",groupInfo.groupId);

        new HttpPostTask(this,params).executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_DELETE_URL);
    }
}
