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 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 java.awt.*;
import java.awt.image.*;

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.MouseEvent;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Screen;
import javafx.stage.Stage;

public class RainbowSetup
{
	static void Setup( Stage primaryStage, Thread primaryThread ) throws IOException
	{
		primaryStage.addEventHandler(MouseEvent.MOUSE_CLICKED, new EventHandler<MouseEvent>()
		{
			@Override
			public void handle(MouseEvent event) 
			{
				System.exit(0);
			}
		});

		double fRateDivisor = 24;//24{With 24 Complete PrintScreen .png s //7//192-ForAnyFullQuickTest//384//468//484//576//555//666//888//1152 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");

		boolean primaryIsFullScreened = true;

		// 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);
		KeyCombination fullScreenedKeyCombination = new KeyCodeCombination(KeyCode.ENTER, KeyCombination.ALT_DOWN);
		primaryStage.setFullScreenExitHint("Alt-Enter To Toggle Full-Screened Mode");
		primaryStage.setFullScreenExitKeyCombination(fullScreenedKeyCombination);

		primaryStage.setX(-100);
		primaryStage.setY(100);
		primaryStage.setWidth( 1920 ); //666
		primaryStage.setHeight( 1080 ); //888

		primaryStage.setResizable(false);

		/*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 + 1)];
		stackPane[0] = new StackPane();
		stackPane[0].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[(int)(fRateDivisor + 1)];
		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");
		WebView browser = new WebView();
		browser.resize(primaryBounds.getWidth(), primaryBounds.getHeight() );
		//browser.setMinSize(primaryBounds.getWidth(), primaryBounds.getHeight() );
		//browser.setPrefSize( primaryBounds.getWidth(), primaryBounds.getHeight() + 10 ); // Important For Full Screened
		WebEngine webEngine = browser.getEngine();
		//webEngine.load("https://news.google.com/news/?ned=us&hl=en&gl=US");
		webEngine.load( "http://www.pixies.zone/BlankWebPage.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
		/*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/SciMagOrderMagiEliteFullHD.png");//SciMagOrderMagiEliteFullHDSkyBlueFunctionTest.png//SciMagOrderMagiEliteFullHDGreenBacking.png//KnightsOfTheSciMagOrderNewPre1.png//BuddhismTemplateHD.png//SciMagOrderMagiEliteFullHD.png
		//origionalBasisImage = new Image("http://www.pixies.zone/Pictures/BuddhismTemplateHD.png");
		Image backgroundBasisImage = new Image("http://www.pixies.zone/Pictures/SciMagOrderMagiEliteBasisBackgroundFullHD.png");//SciMagOrderMagiEliteBasisBackgroundFullHD.png//SciMagOrderMagiEliteBasisBackgroundFullHDWSpotches.png//BuddhismTemplateHD.png
		//backgroundBasisImage = new Image("http://www.pixies.zone/Pictures/BuddhismTemplateHD.png");
		Image firstBackupWorkAroundImage = new Image("http://www.pixies.zone/Pictures/PixieesText.png");//BuyHempStartImage.png, PixiesWillAlwaysGetReincarnatedText.png
		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);
		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");
		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());
		}
		//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 */
		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 ); }//, 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);
			}
		});//*/
	}
}
