package com.wasu.cs.protocol;

import java.util.Set;

import android.net.Uri;
import android.net.Uri.Builder;
import android.os.Handler;

import com.wasu.cs.model.Model;

/**
 * 分页数据获取基类
 * @author LiuYang
 * Created by LiuYang on 7/2/15.
 */
public abstract class BaseListProtocol extends BaseProtocol {

    private int pageNo = 1;
    private int pageSize = 40;
    private String url;
    private Handler handler;
    private DataFetchCallback fetchCallback;
    private boolean mbInFetch = false;

    public BaseListProtocol withPageSize(int pageSize) {
        this.pageSize = pageSize;
        return this;
    }

    public BaseListProtocol withUrl(String url) {
        this.url = url;
        return this;
    }

    public boolean hasNextPage() {
        boolean res = false;

        if(getTotalSize() > pageNo*pageSize) {
            res = true;
        }

        return res;
    }

    public void nextPage() {
    	if (mbInFetch){
    		return;
    	}
    	pageNo++;
        fetchData(handler,url,fetchCallback);
    }

    public int getPageNo() {
        return pageNo;
    }

    public int getPageSize() {
        return pageSize;
    }

    /**
     * 获取分页的数据
     * @return
     */
    public String getRequestUrl() {
    	if (this.url != null){
        	Uri tmp = Uri.parse(this.url);
        	Set<String> keyList = tmp.getQueryParameterNames();
        	Builder build = tmp.buildUpon();
        	build.clearQuery();
        	
        	try{
            	for (String key:keyList){
            		if (key.compareToIgnoreCase("page") == 0){
            			continue;
            		}
            		if (key.compareToIgnoreCase("psize") == 0){
            			continue;
            		}
            		
            		build.appendQueryParameter(key, tmp.getQueryParameter(key));
            	}
        	}catch(Exception e){
        		e.printStackTrace();
        	}
        	build.appendQueryParameter("page", 	String.valueOf(pageNo));
        	build.appendQueryParameter("psize", String.valueOf(pageSize));
        	
        	String query = build.build().toString();
        	
        	return query;
    	}
    	return "";
    }

    public void fetchData(final Handler handler,String urlparam,final DataFetchCallback callback) {
        this.handler = handler;
        this.url = urlparam;
        this.fetchCallback = callback;
        mbInFetch = true;
        fetch(this.getRequestUrl(), new FetchCallback() {
            @Override
            public void onResult(final boolean successed, final BaseProtocol protocol) {
            	if (!successed){
            		pageNo--;
            		if (pageNo < 1){
            			pageNo = 1;
            		}
            	}
            	mbInFetch = false;
            	callback.onResult(successed, successed ? protocol.getData():null);
            }
        }, this);
    }

    public interface DataFetchCallback {
        public void onResult(boolean successed, Model catData);
    }

    abstract public int getTotalSize();

}
