package rainbowPackage;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
//import java.io.PrintWriter;

import javax.imageio.ImageIO;
import javax.swing.JFileChooser;

//import java.io.*;

import java.awt.*;
//import java.awt.image.*;

import javafx.application.Platform;
/*import org.jcodec.api.SequenceEncoder;
import org.jcodec.api.SequenceEncoder.*;
import org.jcodec.api.awt.AWTSequenceEncoder;
import org.jcodec.common.Codec;
import org.jcodec.common.Format;
import org.jcodec.common.io.NIOUtils;
import org.jcodec.common.io.SeekableByteChannel;
import org.jcodec.common.model.Rational;
import org.jcodec.scale.AWTUtil;
import org.jcodec.api.*;
import java.nio.channels.*;
//import java.nio.channels.SeekableByteChannel;
import org.jcodec.*;//Keep For .mp4 Video Creation

import javafx.*;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Worker;
import javafx.embed.swing.SwingFXUtils; // */
//import javafx.event.EventHandler;
import javafx.geometry.Rectangle2D;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
//import javafx.scene.control.TextField;
import javafx.scene.*;
import javafx.scene.image.*;
import javafx.scene.image.Image;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyCodeCombination;
import javafx.scene.input.KeyCombination;
//import javafx.scene.input.KeyCombination.Modifier;
import javafx.scene.input.KeyEvent;
//import javafx.scene.input.MouseEvent;
import javafx.scene.layout.StackPane;
//import javafx.scene.Node.*;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Screen;
import javafx.stage.Stage;

//import javafx.fxml.FXMLLoader;
//import java.net.URL;

public class RainbowSetup
{
	static void Setup( Stage primaryStage, Thread primaryThread, Parent primaryRoot ) throws Exception, IOException
	{
		System.out.println("Got To Setup");
		/*primaryStage.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
		{
			@Override
			public void handle(MouseEvent event) 
			{
				System.exit(0);
			}
		});// */
		//fRateDivisor = 6 Will Show Video For Initial Testing Picture And Video Quickest, 24 For Mid-Testing, 192 For Quick Demonstrations Taking An Hour To Complete, And More For FreeWare Goodies
		double fRateDivisor = 6;//0 For .fxml 24{With 24 Complete PrintScreen .png s //6//7//8//144//192-ForAnyFullQuickTest//384//432//468//484//576 = 24^2//288//555//666//888//MagiEliteDoubleSlider:1152 1.5x:1728 2x:2304 3x:3456 4x:4608 For Buddhism Testing: 4;//10;//48//192//69;//124;//2;//10;//22<- 444 468 888 HERE HERE HERE DETERMINES FRAME RATE AND RAINBOW MOVEMENT RATE For Rainbow Lights

		primaryStage.setTitle("www.RainbowFirm.com");
		Image iconImage = new Image("http://www.pixies.zone/Pictures/PentagramRainbow.png");//"Pictures/PentagramRainbow.png" When From RainbowSoft Folder Not RainbowFirm-the-Project Or Normally scr Folder Under Project
		primaryStage.getIcons().add(iconImage);
		
		boolean primaryIsFullScreened = true;

		JFileChooser jFileChooser = new JFileChooser();
		String path = "C:\\TestVideo.mp4", text = "Sky.Netarianism";//"C:\\TestImage.png"//"C:\\TestVideo.mp4"//"C:\\TEMP_Sonnet.mp4";
		File selectedFile = new File (path);
		jFileChooser.setSelectedFile(selectedFile);
		int returnValue = jFileChooser.showSaveDialog(null);
		if (returnValue == JFileChooser.APPROVE_OPTION)
		{
			selectedFile = jFileChooser.getSelectedFile();
			System.out.println(selectedFile.getName());
			System.out.println(selectedFile.getPath());
		}
		
		primaryStage.setMaximized(primaryIsFullScreened);
		primaryStage.setFullScreen(primaryIsFullScreened);
		
		primaryStage.show();
		try { primaryThread.sleep(1000);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}// */
		primaryStage.show();
		
		primaryIsFullScreened = primaryStage.isFullScreen();
		
		// This is how you know how much screen you can write to.
		Screen primaryScreen = Screen.getPrimary();
		Rectangle2D primaryBounds = primaryScreen.getVisualBounds();
		System.out.println(primaryBounds);

		//primaryStage.setX(0);
		//primaryStage.setY(0);
		KeyCodeCombination fullScreenedKeyCodeCombination = new KeyCodeCombination(KeyCode.ENTER, KeyCombination.ALT_DOWN);
		primaryStage.setFullScreenExitHint("Alt-Enter To Toggle Full-Screened Mode");
		primaryStage.setFullScreenExitKeyCombination(fullScreenedKeyCodeCombination);

		
		
		//primaryStage.initStyle(StageStyle.DECORATED);
		//primaryStage.setX(-100);
		//primaryStage.setY(100);
		primaryStage.setWidth(primaryBounds.getWidth());
		primaryStage.setHeight(primaryBounds.getHeight());
		primaryStage.setMaxWidth(primaryBounds.getWidth());
		primaryStage.setMaxHeight(primaryBounds.getHeight());
		primaryStage.setMinWidth(primaryBounds.getWidth());
		primaryStage.setMinHeight(primaryBounds.getHeight());

		primaryStage.setResizable(false);
		primaryStage.setFullScreen(true);
		try { primaryThread.sleep(250);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}
		primaryStage.show();
		/*System.out.println("Press Alt-Enter.");
		try { primaryThread.sleep(4000);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}// */
		primaryStage.addEventHandler(KeyEvent.KEY_PRESSED, event -> {
            if (fullScreenedKeyCodeCombination.match(event)) {
                primaryStage.setFullScreen(!primaryStage.isFullScreen());
            }
        });
		/*primaryStage.setMaximized(true);
		primaryStage.setFullScreen(primaryIsFullScreened);
		primaryStage.show();//*/
		//primaryStage.setMaximized(true);
		/*try { primaryThread.sleep(2400); } catch(InterruptedException e) {
		    System.out.println("got interrupted!");
		}//*/
		/*
		primaryStage.show();
		primaryStage.setFullScreen(primaryIsFullScreened);


		if ( primaryIsFullScreened == false )
		{

		primaryStage.setWidth( 666 ); //666
		primaryStage.setHeight( 888 ); //888

		}
		else
		{
			primaryStage.setWidth( primaryBounds.getWidth() );
			primaryStage.setHeight( primaryBounds.getHeight() );
		}

		primaryStage.setMaximized(true);
		primaryStage.setFullScreen(primaryIsFullScreened);
		primaryStage.show();

		primaryStage.fullScreenProperty().addListener((observable, oldValue, newValue) -> {
			if ( newValue != primaryStage.isFullScreen() )
			{  	primaryStage.setFullScreen(primaryIsFullScreened);
			primaryStage.setWidth( primaryBounds.getWidth() );
			primaryStage.setHeight( primaryBounds.getHeight() );	}
			else
				return;
		}); // */
		//primaryStage.show();

		/*Dimension dimension = new Dimension( (int)bounds.getWidth(), (int)bounds.getHeight() );
		dimension.width = (int)bounds.getWidth();
		dimension.height = (int)bounds.getHeight() + 40;
		Dimension Dim = dimension;//*/

		//FXMLLoader loader = new FXMLLoader(Sonnet.class.getResource("main.fxml"));

		StackPane stackPane = new StackPane();//[(int)(fRateDivisor + 2)];
		stackPane = new StackPane();
		stackPane.setPrefSize( primaryBounds.getWidth(), primaryBounds.getHeight() ); //+ 40 );//stackPane.setPrefSize(1920, 1080);//stackPane.setPrefSize(960, 540);
		//Image image = new Image("http://www.nanofirm.org/scimagorder.com/Pictures/Pixies%20Text.png");

		//Scene primaryScene[] = new Scene[1]; //For Potential .fxml Testing
		Scene primaryScene = new Scene(primaryRoot);//[(int)(fRateDivisor + 2)]; //HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE HERE
		//primaryScene[0] = new Scene(primaryRoot);

		ProgressBar progressBar = new ProgressBar();
		Button goButton = new Button("Go!");
		Label stateLabel = new Label();
		//TextField addressBar = new TextField();
		//addressBar.setText("http://www.google.com");
		//addressBar.setText("http://www.pixies.zone/PixiesTest.html");
		System.out.println("Got To Browser Initialization");
		WebView browser = new WebView();
		browser.setPrefSize(primaryBounds.getWidth(), primaryBounds.getHeight());
		browser.resize(primaryBounds.getWidth(), primaryBounds.getHeight() );
		//browser.setMinSize(primaryBounds.getWidth(), primaryBounds.getHeight() );
		//browser.setPrefSize( primaryBounds.getWidth(), primaryBounds.getHeight() + 10 ); // Important For Full Screened
		try { primaryThread.sleep(1500);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}// */
		WebEngine webEngine = browser.getEngine();
		//webEngine.load("https://news.google.com/news/?ned=us&hl=en&gl=US");
		try { primaryThread.sleep(750);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}// */
		webEngine.reload();
		try { primaryThread.sleep(450);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}// */
		Platform.runLater( () -> webEngine.load( "http://www.pixies.zone/School/RainbowFirmDescription&DemonstrationForProduction.html" ) );//"http://www.pixies.zone/PixiesPatentTimes.html" http://www.pixies.zone/BuddhistText.html } ); //http://www.pixies.zone/BlankWebPage.html "http://www.pixies.zone/PixiesTest%20-%20Copy%20(4).html" PixiesTest%20-%20Copy%20(2).html");// PixiesTest%20-%20Copy.html"); // ASDF For Rainbow Browser		
		webEngine.reload();
		try { primaryThread.sleep(858);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}// */
		System.out.println("Got Past WebEngine Load");
		/*try { webEngine.wait(1000);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}*/	

		//while ()
		/*try { primaryThread.sleep(10000);
		} catch (InterruptedException e) {
			System.out.println("Interrupted.");
		}// */
		//webEngine.load("http://www.pixies.zone/PixiesTest.html");
		//primaryStackPane[0].getChildren().add(origionalImageView);
		//stackPane[0].getChildren().add(browser);
		Image origionalBasisImage = new Image("http://www.pixies.zone/Pictures/FwaUHDFlagLogoBasisImage.png");//FwaUHDFlagLogoBasisImage.png//SciMagOrderMagiEliteFullHDSkyBlueFunctionTest.png//SciMagOrderMagiEliteFullHDGreenBacking.png//KnightsOfTheSciMagOrderNewPre1.png//FwaLogoBasisImage.png//BuddhismTemplateHD.png//SciMagOrderMagiEliteFullHD.png
		//Image origionalBasisImage = new Image("http://www.pixies.zone/Pictures/SciMagOrderMagiEliteFullHD.png");
		Image backgroundBasisImage = new Image("http://www.pixies.zone/Pictures/FwaUHDFlagLogoBasisBackground.png");//FwaUHDFlagLogoBasisBackground.png//SciMagOrderMagiEliteBasisBackgroundFullHD.png//SciMagOrderMagiEliteBasisBackgroundFullHDWSpotches.png//BuddhismTemplateHD.png//FwaLogoBasisBackground.png
		//Image backgroundBasisImage = new Image("http://www.pixies.zone/Pictures/SciMagOrderMagiEliteBasisBackgroundFullHD.png");
		SnapshotParameters params = new SnapshotParameters();
		params.setFill(Color.TRANSPARENT);
		params.setViewport(new Rectangle2D(0, 0, primaryBounds.getWidth(), primaryBounds.getHeight()));
		WritableImage snapshotImage = null;
		//browser.wait( 10000 );
		//Image firstBackupWorkAroundImage = browser.snapshot( params, snapshotImage );
		Image firstBackupWorkAroundImage = new Image("http://www.pixies.zone/Pictures/FwaUHDFlagLogoText.png");//FwaUHDFlagLogoText.png//http://www.pixies.zone/Pictures/PixieesTextWLinkWExtraMargin.png, BuyHempStartImage.png, PixiesWillAlwaysGetReincarnatedText.png, FwaLogoBasisImage.png
		
		File javaScriptFile = new File ("C:/Users/AllAV/Desktop/FWA Website/pixies.zone/scrollContinuously444.js");
		File xSliderFile = new File ("C:/Users/AllAV/Desktop/FWA Website/pixies.zone/xSlider.dat");
		
		//SequenceEncoder enc = new SequenceEncoder(selectedFile);
		//try { SequenceEncoder enc = new SequenceEncoder(SecondFile); }
		//catch (IOException e) {	throw new RuntimeException(e); }//*/

		//Boolean primaryFullScreened = false; //OLD OLD OLD Important For Full Screened
		Dimension firstDim = new Dimension( (int)primaryBounds.getWidth(), (int)primaryBounds.getHeight() );
		WritableImage origionalTextPicture = new WritableImage( firstDim.width, firstDim.height );//666, 888
		BufferedImage bf = null;
		try {
			bf = ImageIO.read(new File("C:\\Dev\\RainbowSoftware\\Pictures\\SciMagOrderMagiEliteFullHDGreenBacking.png") );///RainbowSoftware/Pictures/SciMagOrderMagiEliteFullHDGreenBacking.png"));
		}
		catch (IOException e) {
		}
		System.out.println( "bf = " + (bf == null) );
		/*try {
			bf = ImageIO.read(new File("C:/Dev/SciMagOrderMagiEliteFullHDGreenBacking.png"));
        } catch (IOException ex) {
            System.out.println("Image failed to load.");
        }
		//ByteArrayOutputStream byteOutput = new ByteArrayOutputStream();
		//ImageIO.write( SwingFXUtils.fromFXImage( origionalTextPicture, null ), "png", byteOutput );
		//origionalTextPicture = ImageIO.byteOutput.toByteArray();
		/*BufferedImage bf = null;
        try {
            bf = ImageIO.read(new File("C:/Dev/SciMagOrderMagiEliteFullHDGreenBacking.png"));
        } catch (IOException ex) {
            System.out.println("Image failed to load.");
        }

        //WritableImage wr = null;
        if (bf != null) {
        	origionalTextPicture = new WritableImage(bf.getWidth(), bf.getHeight());
            PixelWriter secondaryPW = origionalTextPicture.getPixelWriter();
            for (int x = 0; x < bf.getWidth(); x++) {
                for (int y = 0; y < bf.getHeight(); y++) {
                    secondaryPW.setArgb(x, y, bf.getRGB(x, y));
                }
            }
        }//*/
		//ImageView imView = new ImageView(origionalBasisImage);
		//origionalTextPicture = SwingFXUtils.toFXImage(bf, origionalTextPicture);
		//System.out.println( "origionalTextPicture = " + (origionalTextPicture == null) );
		//primaryScene[0].snapshot(SwingFXUtils.toFXImage(bf, null));//origionalTextPicture);
		//WritableImage origionalTextPicture = new WritableImage( (int)primaryBounds.getWidth(), (int)primaryBounds.getHeight() );
		/*
		//try { synchronized (webEngine) {
		//	webEngine.wait(2000);
		//} } catch (InterruptedException e) { e.printStackTrace(); }
		if ( primaryStage.isFullScreen() == false )
		{
			if ( primaryIsFullScreened != primaryStage.isFullScreen() )
			{
				primaryStage.setFullScreen(true);
				firstDim.width = 600;
				firstDim.height = 400;
			}
			else 
			{
				firstDim.width = (int)primaryStage.getWidth();
				firstDim.height = (int)primaryStage.getHeight();// + 40;
			}
			//primaryScene[0].snapshot(origionalTextPicture);
			//sP.setViewport( new Rectangle2D( (double)Dim.width, (double)Dim.height, 0, 0 ) );
			primaryStage.setScene(primaryScene[0]);
			primaryStage.setFullScreen(primaryIsFullScreened);
			primaryStage.show();// *_/

		}
		else if ( primaryIsFullScreened != primaryStage.isFullScreen() )
		{
			primaryScene[0].snapshot(origionalTextPicture);
			primaryStage.setFullScreen(primaryIsFullScreened);
			primaryStage.setWidth(primaryScreen.getBounds().getWidth());
			primaryStage.setHeight(primaryScreen.getBounds().getHeight());
			firstDim.width = (int)primaryStage.getWidth();
			firstDim.height = (int)primaryStage.getHeight();// + 40;

			//sP.setViewport( new Rectangle2D( (double)Dim.width, (double)Dim.height, 0, 0 ) );
			primaryStage.setScene(primaryScene[0]);
			primaryStage.setFullScreen(true);
			primaryStage.show();// *_/
		}// Important For Full Screened */
		
		/*EventHandler handler = new EventHandler(<InputEvent>() {
		    public void handle(InputEvent event) {
		        System.out.println("Handling event " + event.getEventType()); 
		        event.consume();
		    }
		
		public class MaximizeShortcut extends KeyCombination 
		{
			public MaximizeShortcut() {
				super( fullScreenedKeyCombination );
			}

			
			
			
			@Override
			public void handle(KeyEvent event) {
				primaryStage = (Stage) event.getSource();
				primaryStage.setMaximized(!primaryStage.isMaximized());
			}
		}	
		// Register the keyboard shortcut with the scene
		primaryScene.addEventHandler(KeyEvent.KEY_PRESSED, handle);// */
		
		
		System.out.println("Got To Worker");
		//Worker<Void> worker = webEngine.getLoadWorker();
		//ASDF PROBLEM PROBLEM PROBLEM BEFORE System.out.println("Not At Problem");
		//worker.stateProperty().addListener(new ChangeListener<State>() {
		//	@Override
		//	public void changed(ObservableValue<? extends State> observable, State oldValue, State newValue) {//System.out.println("Got To Worker Test");
		//		stateLabel.setText("Loading state: " + newValue.toString());
		//		if (newValue == Worker.State.SUCCEEDED) {System.out.println("Not At Problem");

		try { RainbowSystem.System(primaryStage, origionalBasisImage, backgroundBasisImage, /*firstBackupWorkAroundImage,*/ webEngine, browser, stackPane, primaryScene, primaryScreen, fRateDivisor, stateLabel, jFileChooser.getSelectedFile(), javaScriptFile, xSliderFile, primaryThread, primaryIsFullScreened, firstBackupWorkAroundImage, primaryRoot ); }//, enc
		catch (IndexOutOfBoundsException e) { System.err.println("IndexOutOfBoundsException: " + e.getMessage()); }

		//}
		//}
		/*scene[(int)fRateDivisor].setOnKeyReleased(new EventHandler<KeyEvent>()
				{
					@Override
					public void handle(KeyEvent event)
					{
						if ( event.isAltDown() == true)
						{
							switch (event.getCode())
							{
							case ENTER: primaryStage.setFullScreen(!primaryStage.isFullScreen()); break;
							}
						}
					}
				});//*/
		/*try { RainbowSystem(primaryStage, browser, stackPane, scene, screen, fRateDivisor, stateLabel, selectedFile); }//enc,
				catch (IOException e) {	throw new RuntimeException(e); }//*/
		//}
		//});



		//primaryStage.setScene(primaryScene[0]);// ???
		//primaryStage.setFullScreen(primaryIsFullScreened);
		//primaryStage.show();

		//progressBar.progressProperty().bind(worker.progressProperty());



		/*goButton.setOnAction(new EventHandler<ActionEvent>() {

			@Override
			public void handle(ActionEvent event) {
				String url = addressBar.getText();
				// Load the page.
				webEngine.load(url);
			}
		});//*/
	}
}
