package com.j2medev.chapter3.phonebook.ui;

import javax.microedition.lcdui.*;

import com.j2medev.chapter3.phonebook.*;

public class ListEntryUI extends List implements CommandListener {
    
    private Controller controller;
    private Entry[] entries;
    
    private Command exit = new Command("退出", Command.EXIT, 0);
    private Command edit = new Command("编辑", Command.ITEM, 0);
    private Command add  = new Command("添加",  Command.ITEM, 0);
    private Command remove = new Command("删除", Command.ITEM, 0);
    
    public ListEntryUI(Controller controller) {
        super("联系人列表", List.IMPLICIT);
        this.controller = controller;
        addCommand(exit);
        addCommand(edit);
        addCommand(add);
        addCommand(remove);
        setCommandListener(this);
    }
    
    public void load(Entry[] entries) {
        // 首先清除以前的选项,便于刷新列表
        while(size()>0) {
            delete(0);
        }
        this.entries = entries;
        for(int i=0; i<entries.length; i++) {
            append(entries[i].getName(), null);
        }
    }
    
    public void commandAction(Command c, Displayable d) {
        if(c==exit)
            controller.handleCommand(Controller.APP_EXIT, null);
        if(c==add)
            controller.handleCommand(Controller.SHOW_ADD_ENTRY, null);
        int index = getSelectedIndex();
        if(index==(-1))
            return;
        if(c==edit)
            controller.handleCommand(Controller.SHOW_EDIT_ENTRY, entries[index]);
        if(c==remove)
            controller.handleCommand(Controller.DO_REMOVE_ENTRY, entries[index]);
        if(c==SELECT_COMMAND)
            controller.handleCommand(Controller.SHOW_DETAIL_ENTRY, entries[index]);
    }
    
}