import org.openqa.selenium.By;
import org.openqa.selenium.TimeoutException;

import org.openqa.selenium.Keys;
import java.io.*;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.*;
import java.lang.InterruptedException;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;
import org.openqa.selenium.io.TemporaryFilesystem;
import org.openqa.selenium.support.ui.Wait;
import org.openqa.selenium.support.ui.WebDriverWait;

import org.junit.After;
import java.io.File;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.apache.commons.io.FileUtils;

import java.net.URI;
import java.net.URL;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.io.IOException;
import java.util.Random;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.JavascriptExecutor;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/*
package com.myjava.url;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
 */
public class MAutoScreenTool {

	private static FirefoxProfile Create_FP(String user_agent)
	{
		FirefoxProfile profile = new FirefoxProfile();

		File firebug = new File("firebug-1.11.4-fx.xpi");
		File netExport = new File("netExport-0.8b20.5160.xpi");

		try
		{
			profile.addExtension(firebug);
			profile.addExtension(netExport);
		}
		catch (IOException err)
		{
			System.out.println(err);
			System.exit(1);
		}
		profile.setPreference("app.update.enabled", false);
		profile.setPreference("general.useragent.override",user_agent);

		String domain = "extensions.firebug.";

		profile.setPreference(domain + "currentVersion", "1.11.4-fx");
		profile.setPreference(domain + "allPagesActivation", "on");
		profile.setPreference(domain + "defaultPanelName", "net");
		profile.setPreference(domain + "net.enableSites", true);
		profile.setPreference(domain + "delayLoad", false);

		profile.setPreference(domain + "netexport.alwaysEnableAutoExport", true);
		profile.setPreference(domain + "netexport.showPreview", false);
		profile.setPreference(domain + "netexport.pageLoadedTimeout", "1500");
		profile.setPreference(domain + "netexport.timeout", "120000");

		String hpath = System.getProperty("user.dir") + File.separator + "HAR";

		profile.setPreference(domain + "netexport.defaultLogDir",hpath);
		return profile;
	}

	private static void SaveScreenshot(WebDriver driver, String imgname, int num_scr)
	{
		byte[] buffer = new byte[1024];

		try {
			System.out.println("Saving Screenshots\n");
			FileOutputStream fos = new FileOutputStream(imgname + ".zip");
			String fosname = imgname + ".zip";
			ZipOutputStream zos = new ZipOutputStream(fos);
			for(int i=1;i<=num_scr;i++)
			{
				File screenshot = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
				Thread.sleep(5000);
				String fname = imgname + "_" + Integer.toString(i) + ".png"; 
				System.out.println(fname);
				
				// TakeScreenshot
				
				FileUtils.copyFile(screenshot, new File(fname));
				
				// Add to zip

				ZipEntry ze = new ZipEntry(fname);
				zos.putNextEntry(ze);
				FileInputStream in = new FileInputStream(fname);
				int len;
				while ((len = in.read(buffer)) > 0) {
					zos.write(buffer, 0, len);
				}

				in.close();
				zos.closeEntry();
			}
			zos.close();
			fos.close();
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	private static String locateHARfile(String hpath)
	{
		String files,filename;
		File dir = new File(hpath);
		File[] LoF = dir.listFiles();

		System.out.println("Searching har file");
		for(int i=0;i<LoF.length;i++)
		{
			if(LoF[i].isFile())
			{
				files = LoF[i].getName();
				if(files.endsWith(".har"))
				{
					filename = hpath + File.separator + files;
					System.out.println("File found! Harfile name - " +filename);
					return filename;
				}
			}
		}
		return null;
	}

	private static int TrackerFired(Scanner fileScanner, String phrase)
	{
		Pattern pattern = Pattern.compile(phrase);
		Matcher matcher = null;
		while(fileScanner.hasNextLine())
		{
			String line = fileScanner.nextLine();
			matcher = pattern.matcher(line);
			if(matcher.find())
			{
				System.out.println("match found\n");
				return 1;
			}
		}
		return 0;
	}

	private static void deleteScreenshot(String s3_path, String imgname, int num_scr)
	{
		//If tracker isnt fired, delete the screenshots
		try{
			System.out.println("Deleting Screenshots from local server\n");
			String fosname = imgname + ".zip";
			for(int i=1;i<=num_scr;i++)
			{
				String fname = imgname + "_" + Integer.toString(i) + ".png"; 
				System.out.println(fname);
				File del_img = new File(fname);
				if(del_img.exists())
					del_img.delete();
			}
			System.out.println("deleting zip - " + fosname);
			File del_zip = new File(fosname);
			if(del_zip.exists())
				del_zip.delete();
		}catch (Exception e){
			System.out.println(e);
			System.exit(1);
		}

	}
	
	private static void UploadtoS3(String s3_path, String imgname, int num_scr){
		try {
			System.out.println("Upload to S3\n");
			String fosname = imgname + ".zip";
			String s3_fosname = s3_path + File.separator + imgname + ".zip";

			for(int i=1;i<=num_scr;i++)
			{
				String fname = imgname + "_" + Integer.toString(i) + ".png"; 

				String s3_fname = s3_path + File.separator + fname;

				String cmd = File.separator + "home" + File.separator + "rohit.gautam" + File.separator + "s3cmd-1.0.1" + File.separator + "s3cmd put " + fname + " " + s3_fname;
				System.out.println(cmd);
				Process p = Runtime.getRuntime().exec(cmd);
				try{
					p.waitFor();
				}
				catch(InterruptedException e){
					System.out.println("not uploaded\n");
					System.exit(1);
				}
			}
			System.out.println("uploading zip - " + s3_fosname);
			String cmd = File.separator + "home" + File.separator + "rohit.gautam" + File.separator + "s3cmd-1.0.1" + File.separator + "s3cmd put " + fosname + " " + s3_fosname;
			Process p = Runtime.getRuntime().exec(cmd);
			try{
				p.waitFor();
			}
			catch(InterruptedException e){
				System.out.println("not uploaded\n");
				System.exit(1);
			}
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}

	private static String getUserAgentString(String device)
	{
		String useragent_string="";
		if(device.equals("iphone"))
			useragent_string="Mozilla/5.0 (iPhone; CPU iPhone OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3";
		else if(device.equals("ipad"))
			useragent_string="Mozilla/5.0 (iPad; CPU OS 5_0 like Mac OS X) AppleWebKit/534.46 (KHTML, like Gecko) Version/5.1 Mobile/9A334 Safari/7534.48.3";
		else
			useragent_string="Mozilla/5.0 (Linux; U; Android 4.0.3; ko-kr; LG-L160L Build/IML74K) AppleWebkit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
		return useragent_string;
	}
	public static void main(String[] args) {

		try{

			String ref_url = args[0];
			String cid = args[1];
			String ad_id = args[2];
			String channel_id = args[3];
			String device = args[4];
			String ad_format = args[5];
			String imgname = args[6];
			
			System.out.println(ref_url);		
			System.out.println(cid);		
			System.out.println(ad_id);		
			System.out.println(channel_id);		
			System.out.println(device);		
			System.out.println(ad_format);		
			System.out.println(imgname);		

			String hpath = System.getProperty("user.dir") + File.separator + "HAR";
			
			String useragent_string = getUserAgentString(device);

			FirefoxProfile profile = Create_FP(useragent_string);
			WebDriver driver = new FirefoxDriver(profile);

			String Url = "";
			if(device.equals("androidphone"))
				Url = "http://www.android-emulator.org"; 
			else if(device.equals("iphone"))
				Url = "http://www.iphone5simulator.com";
			else if(device.equals("ipad"))
				Url = "http://www.ipadpeek.com";
			else if(device.equals("androidtablet"))
				Url = "http://www.tablet-emulator.org";

			System.out.println(Url);

			Random randomGenerator = new Random();

			System.out.println(ref_url);
			// Cache bursting

			try{
				driver.get(Url + "?" + randomGenerator.nextInt(1000));
			}catch(Exception e){
				System.out.println(e);
				System.exit(1);
			}

			WebElement element;

			if(device.equals("iphone"))
				element = driver.findElement(By.id("weburl"));
			else	
				element = driver.findElement(By.id("url"));

			element.clear();
			element.sendKeys(ref_url);
			element.sendKeys(Keys.RETURN);
			//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
			WebElement frame;
			if(device.equals("iphone"))
				frame = driver.findElement(By.id("mobileframe"));
			else
				frame = driver.findElement(By.id("frame"));
			driver.switchTo().frame(frame);

			try{
				(new WebDriverWait(driver, 60)).until(new ExpectedCondition<Boolean>() {
						public Boolean apply(WebDriver driver) {
						return ((JavascriptExecutor)driver).executeScript("return document.readyState").equals("complete");
						}   
						}); 
				driver.switchTo().defaultContent();
			} catch(TimeoutException e)
			{
				System.out.println(e);
				System.exit(1);
			}

			//Taking Screenshots
			
			String s3_bkt = "s3://rohit_g";
			String s3_path = s3_bkt + File.separator + "AST" + File.separator + "Screenshots" + File.separator + cid + File.separator + ad_id + File.separator + channel_id + File.separator + device;
			int num_scr=5;
			if(ad_format.equals("banner"))
				num_scr=1;
			SaveScreenshot(driver,imgname,num_scr);

			try{
				// Searching Har file
				String filename = locateHARfile(hpath);

				if(filename==null)
				{
					System.out.println("har not found\n");
					deleteScreenshot(s3_path,imgname,num_scr);
					System.exit(1);
				}
	
				Scanner fileScanner = new Scanner (new File(filename));

				// Matching pattern to check if tracker fired

	//			String phrase = "serve.vdopia.com/adserver/(iphone)*trk/vi/" + cid + "/" + ad_id + "/" + channel_id;
				String phrase = "adserver/(iphone)*trk/vi/" + cid + "/" + ad_id + "/" + channel_id;
				System.out.println("Searching pattern - " + phrase);
				int tracker_found = TrackerFired(fileScanner,phrase);

				
				if(tracker_found!=0)
					UploadtoS3(s3_path,imgname,num_scr);
				else
					System.out.println("Match not found");
				deleteScreenshot(s3_path,imgname,num_scr);

				if(tracker_found==0)
					System.out.println("None");
				
				//Remove the har file

//				System.out.println("Deleting har file");
				File delfile = new File(filename);
				delfile.delete();
//				TemporaryFilesystem tempFS = TemporaryFilesystem.getDefaultTmpFS();
//				tempFS.deleteTemporaryFiles();
				
				driver.quit();
			}catch(Exception e){
				System.out.println(e);
				deleteScreenshot(s3_path,imgname,num_scr);
				System.exit(1);

			}
		}catch(Exception e){
			System.exit(1);
		}
	}
}
