/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package cz.kiwi.cometd.client;

import cz.kiwi.cometd.listener.CommandChannelListener;
import cz.kiwi.cometd.listener.ContentChannelListener;
import cz.kiwi.cometd.utils.CometdClientUtils;
import cz.kiwi.cometd.utils.ConfigResourceBundle;
import cz.kiwi.cometd.utils.ExternalDataLoader;
import java.util.HashMap;
import java.util.Map;
import org.cometd.bayeux.Message;
import org.cometd.bayeux.client.ClientSessionChannel.MessageListener;
import org.cometd.client.BayeuxClient;
import org.cometd.client.transport.ClientTransport;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * @author esner
 */
public class BayeuxKiwiClient extends BayeuxClient {
    
    final static Logger logger = LoggerFactory.getLogger(BayeuxKiwiClient.class);
    
    private MessageListener contentChannelListener;
    private MessageListener commandChannelListener;
    
    public BayeuxKiwiClient(String url, ClientTransport transport) {
        super(url, transport);
    }

    @Override
    public void onFailure(Throwable x, Message[] messages) {
        logger.error("onFailure: " + x.getMessage());
        //avoid throwing exceptions
        //super.onFailure(x, messages);
    }
    
    public void subscribeChannels() {
        contentChannelListener = new ContentChannelListener();
        commandChannelListener = new CommandChannelListener();
        
        this.getChannel(CometdClientUtils.CONTENT_CHANNEL).subscribe(contentChannelListener);
        this.getChannel(CometdClientUtils.COMMAND_CHANNEL).subscribe(commandChannelListener);
    }
    
    public void unsubscribeChannels() {
        if (contentChannelListener != null)
            this.getChannel(CometdClientUtils.CONTENT_CHANNEL).unsubscribe(contentChannelListener);
        
        if (commandChannelListener != null)
            this.getChannel(CometdClientUtils.COMMAND_CHANNEL).unsubscribe(commandChannelListener);
    }
    
    public void registerClient() {
        logger.info("Registering player: " + ConfigResourceBundle.getInstance().getObject("deviceID"));
        
        Map<String, Object> data = new HashMap<String, Object>();
        
        data.put("id", ConfigResourceBundle.getInstance().getObject("deviceID"));
        data.put("accessCode", ConfigResourceBundle.getInstance().getObject("accessCode"));
        
        String timestamp = ExternalDataLoader.getInstance().getUpdateTimestamp();
        
        data.put("updateTimestamp", timestamp != null ? timestamp : "");
        
        System.out.println(data.toString());
        
        this.getChannel(CometdClientUtils.CONTROL_CHANNEL).publish(data);
    }   
}
