/* 
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER
 * Copyright 2009 Sun Microsystems, Inc. All rights reserved. Use is subject to license terms. 
 * 
 * This file is available and licensed under the following license:
 * 
 * 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.
 */
package rssviewer;

import javafx.animation.Timeline;
import javafx.animation.KeyFrame;
import javafx.animation.Interpolator;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import javafx.scene.Scene;
import javafx.scene.paint.Color;
import javafx.scene.shape.Rectangle;
import javafx.io.http.HttpRequest;
import javafx.io.http.HttpHeader;

import rssviewer.model.Channel;
import rssviewer.model.Item;
import rssviewer.parser.RSSPullParser;
import rssviewer.view.ControlPanel;
import rssviewer.view.RSSViewer;

import java.lang.Exception;
import java.lang.Class;
import java.applet.Applet;

var channel : Channel[];

var stageX = 280.0;
var stageY = 140.0;
var stageDragInitialX:Number;
var stageDragInitialY:Number;
// Is running as Applet?
public var inBrowser = "true".equals(FX.getArgument("isApplet") as String);
public var jsMode = "true".equals(FX.getArgument("js_mode") as String);
 
var rssViewer = RSSViewer { };
var controlPanel = ControlPanel { };

public function loadChannel(rssURL : String) {
    
    println("Loading RSS Data...");   
    println("URL: {rssURL}");
    
    delete channel;
    
    var httpRequestError: Boolean = false;
    
    // Submit HttpRequest    
    var request: HttpRequest = HttpRequest {
                
        location: rssURL
        method: HttpRequest.GET
        
        onException: function(exception: Exception) {
            exception.printStackTrace();
        }
                    
        onResponseCode: function(responseCode:Integer) {
            if (responseCode != 200) {
                println("failed, response: {responseCode} {request.responseMessage}");
            }
        }
                        
        onInput: function(input: java.io.InputStream) {
            
            try {
                var parser = RSSPullParser{};
                channel = parser.parse(input);                
            } finally {
                input.close();
            }
        }
        
        onDone: function() { 
            
            if((sizeof channel) > 0) {    
                println("Channel {channel[0]}");
                if(inBrowser) {
                    showTableData();
                } else {
                    rssViewer.channel = channel[0];
                }
            }
        }
    }
    
    request.setHeader(HttpHeader.USER_AGENT, "Mozilla/4.0");
    request.start();
}

public function showTableData() {
    setChannelData("{channel[0].getTableData()}");
}

public function showNextItem() {
    setChannelData("{channel[0].getNextTableData()}");
}

public function showPrevItem() {
    setChannelData("{channel[0].getPrevTableData()}");
}

public function run() {

    if(inBrowser and jsMode) { 
        
        var stage = Stage {
            x:0 y: 0
            title: "RSS Viewer"
            scene: Scene { content: [ controlPanel ] }
            height: 80
        }
        
    } else {

        // Drag Bar
        var dragBar:Rectangle = Rectangle {
            width: 240
            height: 50
            fill: Color.TRANSPARENT
            visible: bind (not inBrowser)
            onMousePressed: function(e) {
                stageDragInitialX = e.screenX - stage.x;
                stageDragInitialY = e.screenY - stage.y;
            }
             onMouseDragged: function(e) {
                stage.x = e.screenX - stageDragInitialX;
                stage.y = e.screenY - stageDragInitialY;
             }
        }
        
        var stage:Stage = Stage {
            title: "RSS Viewer"
            scene: Scene { 
                content: [ rssViewer, dragBar ] 
                fill: Color.TRANSPARENT
            }
            x: bind stageX with inverse
            y: bind stageY with inverse
            style: StageStyle.TRANSPARENT
        }        
    }
    
    var url = FX.getArgument("rss_url");
    if(url == null) { url = "http://rss.news.yahoo.com/rss/world"; }
    loadChannel(url.toString());
}

/*******************************************************************
 * JavaFX Script <-> JavaScript Interaction [Only for Browser]
 *******************************************************************/

public function setChannelData(tableData : String) {
    
    if(not jsMode) { return; }    
    
    try {
        
        // Get the Applet instance
        var applet: Applet = FX.getArgument("javafx.applet") as Applet;
        var window = netscape.javascript.JSObject.getWindow(applet);
        window.call("updateChannelData", ["{tableData}"]);
        
    } catch (e:java.lang.Exception) {
        println("Exception thrown while trying to invoke JavaScript methods!");
        e.printStackTrace();
    }
}