/*  
 * Copyright (c) 2008, Sun Microsystems, Inc.
 * 
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 
 *  * Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *  * Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *  * Neither the name of Sun Microsystems nor the names of its contributors
 *    may be used to endorse or promote products derived from this software
 *    without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * 
 *  Note:  In order to comply with the binary form redistribution 
 *         requirement in the above license, the licensee may include 
 *         a URL reference to a copy of the required copyright notice, 
 *         the list of conditions and the disclaimer in a human readable 
 *         file with the binary form of the code that is subject to the
 *         above license.  For example, such file could be put on a 
 *         Blu-ray disc containing the binary form of the code or could 
 *         be put in a JAR file that is broadcast via a digital television 
 *         broadcast medium.  In any event, you must include in any end 
 *         user licenses governing any code that includes the code subject 
 *         to the above license (in source and/or binary form) a disclaimer 
 *         that is at least as protective of Sun as the disclaimers in the 
 *         above license.
 * 
 *         A copy of the required copyright notice, the list of conditions and
 *         the disclaimer will be maintained at 
 *         https://hdcookbook.dev.java.net/misc/license.html .
 *         Thus, licensees may comply with the binary form redistribution
 *         requirement with a text file that contains the following text:
 * 
 *             A copy of the license(s) governing this code is located
 *             at https://hdcookbook.dev.java.net/misc/license.html
 */

package org.homebrew;

import java.awt.BorderLayout;
import java.awt.Container;
import java.net.InetAddress;
import java.util.ArrayList;

import javax.media.ControllerEvent;
import javax.media.ControllerListener;
import javax.tv.xlet.Xlet;
import javax.tv.xlet.XletContext;

import org.bluray.ui.event.HRcEvent;
import org.dvb.event.UserEvent;
import org.havi.ui.HScene;
import org.havi.ui.HSceneFactory;


public class MyXlet implements Xlet, ControllerListener {

    private HScene scene;
    private Container gui;
    private XletContext context;
    private final ArrayList messages = new ArrayList();
    
   
    
    public void initXlet(XletContext context) {
        this.context = context;
        
        scene = HSceneFactory.getInstance().getDefaultHScene();
        
        
        messages.add("Hi, this is a small homebrew test.");
        messages.add("let's start with a RSS reader");
        messages.add("");
        
        gui = new Screen(messages);

        gui.setSize(1920, 1080);  // BD screen size
        scene.add(gui, BorderLayout.CENTER);
        
        try {
			//InetAddress ia = InetAddress.getByName("www.yahoo.com");
			//messages.add("Network Access: IP resolution of www.yahoo.com: " + ia.getHostAddress());
		
			HttpClient c = new HttpClient("http://www.nytimes.com/services/xml/rss/nyt/HomePage.xml");
			c.connect("GET");
			ArrayList text = c.getResponse();
			c.disconnect();
			
			String currentheadline = "";
			String currentheadlinedate = "";
			for(int i=0;i<text.size();i++) {
				
				
				String line = text.get(i).toString();
				int pos = line.indexOf("<title>");
				if (pos > -1 && !line.trim().startsWith("<title>NYT")) {
					currentheadline = line.substring(pos+7, line.indexOf("</title>"));
				} else {
					pos = line.indexOf("<pubDate>");
					if (pos > -1) {
						currentheadlinedate = line.substring(pos+9, line.indexOf("</pubDate>"));
						messages.add("[" + currentheadlinedate + "] " + currentheadline);
					}
				}
			}
			
			
    	} catch (Exception e) {
			messages.add(e.getMessage());
		}
    

        scene.validate();    
        
	
    }

    public void startXlet() {
        gui.setVisible(true);
        scene.setVisible(true);
        gui.requestFocus();
    }

    public void pauseXlet() {
        gui.setVisible(false);
    }

    public void destroyXlet(boolean unconditional) {
        scene.remove(gui);
        scene = null;
    }
       
    
    /**
     * Callback from the system via UserEventListener when a remote
     * control keypress is received.
     **/
    public synchronized void userEventReceived(UserEvent e) {
        if (e.getType() == HRcEvent.KEY_PRESSED) {
            switch(e.getCode()){
            
            case HRcEvent.VK_POPUP_MENU:
                popupKeyPressed();
                break;

            case HRcEvent.VK_0:
            case HRcEvent.VK_1:                
            case HRcEvent.VK_2:
            case HRcEvent.VK_3:
            case HRcEvent.VK_4:
            case HRcEvent.VK_5:
            case HRcEvent.VK_6:
            case HRcEvent.VK_7:
            case HRcEvent.VK_8:
            case HRcEvent.VK_9:
                numberKeyPressed(e.getCode() - HRcEvent.VK_0);
                break;

            case HRcEvent.VK_COLORED_KEY_0:
            case HRcEvent.VK_COLORED_KEY_1:
            case HRcEvent.VK_COLORED_KEY_2:
            case HRcEvent.VK_COLORED_KEY_3:
            case HRcEvent.VK_COLORED_KEY_4:
            case HRcEvent.VK_COLORED_KEY_5:
                colorKeyPressed(e.getCode() - HRcEvent.VK_COLORED_KEY_0);
                break;
                
            case HRcEvent.VK_ENTER:
                enterKeyPressed();
                break;

            case HRcEvent.VK_LEFT:
                arrowLeftKeyPressed();
                break;

            case HRcEvent.VK_RIGHT:
                arrowRightPressed();
                break;

            case HRcEvent.VK_UP:
                arrowUpPressed();
                break;

            case HRcEvent.VK_DOWN:
                arrowDownPressed();
                break;

            }            
        }    
    }
    
    /**
     * Subclasses should override this if they're interested in getting
     * this event.
     **/
    protected void numberKeyPressed(int value){}

    /**
     * Subclasses should override this if they're interested in getting
     * this event.
     **/
    protected void colorKeyPressed(int value){}

    /**
     * Subclasses should override this if they're interested in getting
     * this event.
     **/
    protected void popupKeyPressed(){}

    /**
     * Subclasses should override this if they're interested in getting
     * this event.
     **/
    protected void enterKeyPressed(){}

    /**
     * Subclasses should override this if they're interested in getting
     * this event.
     **/
    protected void arrowLeftKeyPressed(){}

    /**
     * Subclasses should override this if they're interested in getting
     * this event.
     **/
    protected void arrowRightPressed(){}

    /**
     * Subclasses should override this if they're interested in getting
     * this event.
     **/
    protected void arrowUpPressed(){}

    /**
     * Subclasses should override this if they're interested in getting
     * this event.
     **/
    protected void arrowDownPressed(){}

	public void controllerUpdate(ControllerEvent arg0) {
		// TODO Auto-generated method stub
		
	}

    
}
