package uploadAssets;

/**
* Program Create Group
* Author  Janet Frank
* Date    01/20/2016
* Description:  This program will perform the following steps to create a group:
*               1.  It will login to the Brio web site (briotest.brio.viddler.com)
*               2.  Once on the assets view page it will then select the action to
*                   upload a new video
*               3.  Once in the upload modal the file explorer is opened and then
*                   the file name in the input file is copied and pasted into the
*                   file name area of the explorer
*               4.  The file is uploaded and the title and description are added
*               5.  The browser is then closed and the test completed.
* Group file MUST contain the following data as .CSV file with the first line as a header :
* 				1.  title
* 				2.  asset description
* 				3.  file to upload
*  Arguments passed via command line (all are required) :       
*               Changed to use arguments from the command line
*               1.  file name that contains groups to load.
*               2.  admin user name
*               3.  admin password
*               4.  web site to load
*             
*/

import java.util.concurrent.TimeUnit;


//Selenium imports
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.Select;

import java.util.List;

//Java imports
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.datatransfer.StringSelection;
import java.awt.event.KeyEvent;
import java.io.*;

public class uploadAssets {
	// Variables to set up webdriver and selenium verification errors
		private static WebDriver driver;
	// Variables for fields passed to main method from command line	
	    private static String fileName = null;
		private static String adminUser = null;
		private static String adminPassword = null;
		private static String baseUrl;
	// Variables for asset data from file passed via command line
		private static String assetName = null;
		private static String assetDesc = null;
		private static String uploadFile = null;
		private static int groupIndex = 0;
		 
		public static void main(String[] args) throws Exception {
		    driver = new FirefoxDriver();
		    driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
		    driver.manage().window().maximize();

		// Load variables with arguments from command line
		    fileName = args[0];
		    adminUser = args[1];
			adminPassword = args[2];
			baseUrl = args[3];
		// Open browser to login page of url passed from command line    
		    driver.get(baseUrl + "/login");
		// Get file containing assets to be created
		    String assetsFile = fileName;
		  
	    //Create object of FileReader
		    FileReader assetsInputFile = new FileReader(assetsFile);

	    //Instantiate the BufferedReader Class
		    BufferedReader assetBufferReader = new BufferedReader(assetsInputFile);
		        
	    //Variable to hold the one line data
		    String assets = assetBufferReader.readLine();  // first line will contain the headers
		    assets = assetBufferReader.readLine();  // This will be the first line of data.
		    
	    // Login as an admin user
		    driver.findElement(By.name("email_address")).clear();
	    	driver.findElement(By.name("email_address")).sendKeys(adminUser);
	    	driver.findElement(By.name("password")).clear();
	    	driver.findElement(By.name("password")).sendKeys(adminPassword);
	    	driver.findElement(By.cssSelector("button.button")).click();
	    // Loop through file until no more records
		    while (assets != null)
		      {
		// Split the CSV file into separate variables for the asset data to be populated
		    	String[] assetValues = assets.split(",");
		    	assetName = assetValues[0];
		    	assetDesc = assetValues[1];
		    	uploadFile = assetValues[2];
		    	groupIndex = Integer.parseInt(assetValues[3]);
	 	//	    uploadFile = assetValues[2];
		// Find the Upload link and click it -- Use javascript executor for this function
		    	JavascriptExecutor js = (JavascriptExecutor)driver;
		    	WebElement uploadLink = driver.findElement(By.xpath("/html/body/div[1]/section/div/article/div[2]/a"));
		    	System.out.println(uploadLink);
		    	Thread.sleep(5000);
		    	js.executeScript("arguments[0].click();", uploadLink);
	   	// Upload asset avatar as profile picture for asset
		   // Click the Upload logo button
		     	driver.findElement(By.xpath("/html/body/div[1]/section/div/article/div[2]/ul/li[2]/a")).click(); 
		   // Click within the cropper tool to open File Explorer
		     	driver.findElement(By.xpath("/html/body/div[5]/div[2]/div/form/div[1]")).click();
	/*	   // Set the clipboard data to the logo file to use
		        setClipboardData(uploadFile);
		   // Delay
		        Thread.sleep(3000);
		   //  Use the Robot object to simulate the explorer activity
		        Robot robot = new Robot();
		        robot.keyPress(KeyEvent.VK_CONTROL);
		        robot.keyPress(KeyEvent.VK_V);
		        robot.keyRelease(KeyEvent.VK_V);
		        robot.delay(3000);
		        robot.keyRelease(KeyEvent.VK_CONTROL);
		        robot.keyPress(KeyEvent.VK_ENTER); 
		        robot.waitForIdle();
		        robot.delay(3000);
		        robot.keyRelease(KeyEvent.VK_ENTER);
		        robot.waitForIdle();
		    // Delay so that open is executed and explorer is closed
		        robot.delay(3000);
		        Thread.sleep(5000); */
		     	Thread.sleep(2000); // wait for page load   
		     	Runtime.getRuntime().exec("C:\\Users\\Janet\\Documents\\uploadFile.exe " + uploadFile);
		  //   	Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "C:\\Users\\Janet\\Documents\\uploadFile_x64a.exe");
	        // Use the Actions object to click the Save button
		        WebElement saveLink = driver.findElement(By.xpath("/html/body/div[5]/div[2]/div/form/div[1]/div[1]/div/button[1]"));
		    	Actions actions = new Actions(driver);
		    	actions.moveToElement(saveLink);
		    	actions.click();
		    	actions.build().perform();  
		    	Thread.sleep(3000);
		//  Find element for asset name and populate with data from file
		    	WebElement titleLink = driver.findElement(By.xpath("/html/body/div[5]/div[2]/div/form/div[2]/input[2]"));
		    	Thread.sleep(1000);
		    	actions = new Actions(driver);
		    	actions.moveToElement(titleLink);
		    	actions.click();
		    	actions.sendKeys(assetName);
		    	actions.build().perform();  
		    	Thread.sleep(3000);
	//	    	driver.findElement(By.name("title")).clear();
	//	    	driver.findElement(By.name("title")).sendKeys(assetName);
	  	//  Find element for asset description and populate with data from file
		    	WebElement descLink = driver.findElement(By.xpath("/html/body/div[5]/div[2]/div/form/div[2]/textarea"));
		    	Thread.sleep(1000);
		    	actions = new Actions(driver);
		    	actions.moveToElement(descLink);
		    	actions.click();
		    	actions.sendKeys(assetDesc);
		    	actions.build().perform();  
		    	Thread.sleep(3000);
	//	    	driver.findElement(By.name("description")).clear();
	//	    	driver.findElement(By.name("description")).sendKeys(assetDesc);
		 // Submit changes
		     	WebElement submitLink = driver.findElement(By.xpath("/html/body/div[5]/div[2]/div/form/div[2]/input[3]"));
		    	actions = new Actions(driver);
		    	actions.moveToElement(submitLink);
		    	actions.click();
		    	actions.build().perform();  
	   	// Edit Media just added to add it to a group
		    	js = (JavascriptExecutor)driver;
		    	WebElement editLink = driver.findElement(By.xpath("/html/body/div[1]/section/div/article/div[4]/div/div/div[1]/div/table/tbody/tr[2]/td[10]/a[1]"));
		    	System.out.println(editLink);
		    	Thread.sleep(5000);
		    	js.executeScript("arguments[0].click();", editLink);
		// Get the available groups and select the one based on the index in the file
		    	List <WebElement> groups = new Select(driver.findElement(By.name("avail_groups"))).getOptions();
			    groups.get(groupIndex).click();
		// Add the media to the selected group
			    driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/div[4]/div[2]/a[1]")).click();
		// Publish Now
			    driver.findElement(By.xpath("/html/body/div[1]/section/div/article/form/input[3]")).click();
		// Read next line in file
		    	assets = assetBufferReader.readLine();
		      } // End while loop
		// close assets file and browser
		      assetBufferReader.close();
		      driver.quit();
		}
		
	//  Method to load Clipboard with filename of logo to upload
		public static void setClipboardData(String string) {
			   StringSelection stringSelection = new StringSelection(string);
			   Toolkit.getDefaultToolkit().getSystemClipboard().setContents(stringSelection, null);
		}
	

}
