001package gu.dtalk.client;
002
003import com.alibaba.fastjson.JSONObject;
004import com.alibaba.fastjson.util.TypeUtils;
005import gu.dtalk.Ack;
006import gu.dtalk.BaseItem;
007import gu.dtalk.MenuItem;
008import gu.dtalk.ItemType;
009import gu.simplemq.exceptions.SmqUnsubscribeException;
010import static gu.dtalk.CommonUtils.*;
011import static com.google.common.base.Preconditions.*;
012
013/**
014 * 渲染引擎<br>
015 * 用于显示从设备端收到的消息
016 * @author guyadong
017 *
018 */
019public class RenderEngine extends TextMessageAdapter<JSONObject>{
020        private String currentPath;
021        private MenuItem root;
022        private Ack<?> lastAck;
023
024        public Ack<?> getLastAck() {
025                return lastAck;
026        }
027
028
029        public RenderEngine() {
030        }
031
032        
033        @Override
034        public void onSubscribe(JSONObject resp) throws SmqUnsubscribeException {
035                super.onSubscribe(resp);
036                lastAck = null;
037                if(isAck(resp)){
038                        Ack<?> ack = TypeUtils.castToJavaBean(resp, Ack.class);
039                        lastAck = TypeUtils.castToJavaBean(resp, Ack.class);
040                        render.rendeAck(ack, true);
041                }else if(isItem(resp)){
042                        BaseItem item = ItemType.parseItem(resp);
043                        if(item instanceof MenuItem){
044                                MenuItem menu = (MenuItem)item;
045                                currentPath = menu.getPath();
046                                if(isRoot(resp)){
047                                        root = menu;
048                                }else{
049                                        checkState(root!=null," root menu is uninitialized");
050                                        // 更新root中当前菜单项内容
051                                        root.getChildByPath(currentPath).getParent().updateChild(menu);
052                                }
053                                render.rendeItem(menu);
054                        }else{
055                                System.out.printf("UNSUPPORTED ITEM RENDE TYPE:%s\n", item.getCatalog());
056                        }
057                }else{
058                        System.out.printf("UNKNOW TYPE:%s\n", resp.toString());
059                }
060        }
061
062        public MenuItem getCurrentLevel() {
063                return checkNotNull(root).findMenu(currentPath);
064        }
065        public MenuItem getRoot() {
066                return root;
067        }
068        public RenderEngine reset(){
069                currentPath = null;
070                root = null;
071                return this;
072        }
073        public void paint(){
074                render.rendeItem(getCurrentLevel());                            
075        }
076}