package com.kcshu.ssdb.tabs;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.custom.CTabFolder;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.TreeItem;
import org.nutz.ssdb4j.spi.Cmd;
import org.nutz.ssdb4j.spi.Response;

import com.kcshu.ssdb.Images;
import com.kcshu.ssdb.domain.TabType;
import com.kcshu.ssdb.tabs.editor.KeyValueEditorTab;

/**
 * @author zhouhaichao(a)2008.sina.com
 * @version 1.0 & Nov 26, 2014 9:26:40 PM
 */
public class KeyValueTab extends ShowTab
{
    public KeyValueTab(CTabFolder tabFolder, TreeItem item){
        super(tabFolder, item);
    }

    @Override
    public void beforeInitView(){
        String tabName = "键值对@" + treeItem.getParentItem().getText() ;
        self.setData(TAB_TYPE, TabType.HASH);
        self.setImage(Images.get("key"));
        self.setText(tabName);
    }
    
    @Override
    public List<String[]> getDataTask()
    {
        List<String[]> datas = new ArrayList<String[]>();
        Cmd cmd = getSortOrder()?Cmd.scan:Cmd.rscan;
        Response scanRes = get(cmd,startKey,"",size);
        if(scanRes.ok()) {
            List<String> keys = scanRes.listString();
            for (int i = 0; i < keys.size(); i+=2)
            {
                String key = keys.get(i);
                String value = keys.get(i+1);
                datas.add(new String[] {key,value,"1"});
            }
        }
        return datas;
    }
    
    @Override
    public String[] getSingleTask(String key)
    {
        Response res = get(Cmd.get,key);
        if(res.ok()){
            return new String[] {key,res.asString(),"1"};
        }else{
            return null;
        }
    }
    
    @Override
    public void deleteTask(List<String> delkeys)
    {
        for (String string : delkeys){
            get(Cmd.del,string);
        }
    }

    @Override
    protected boolean showKeyValueTab(Composite kvCom, String key)
    {
        return new KeyValueEditorTab(this).showKeyValueTab(kvCom, key);
    }
}
