import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONArray;
import org.json.JSONObject;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;


public class MainFinalizer
{

	public static void main(String[] args) throws Exception
	{
		PrintWriter nonworking = new PrintWriter("Notfinalized.txt", "UTF-8");
		try
		{

			//If within a specific app, it may actually submit the app_icon of that app!
			if( new File( System.getProperty("user.dir"), "images" ).isDirectory() || 
				new File( System.getProperty("user.dir"), "screenshots" ).isDirectory() )
			{
				System.err.println("Please run this from directory without screenshots/images/appicon metadata");
				return;
			}
			
			FirefoxProfile noCheck = new FirefoxProfile();
			//Work in Firefox 43+:
			noCheck.setPreference("xpinstall.signatures.required", false);
			FirefoxDriver mybrowser = new FirefoxDriver( noCheck );
			
			//TODO get cookies with http://www.rubydoc.info/gems/spaceship/0.31.4/Spaceship/Client#cookie-instance_method
			//and pass it to Java, then don't have to open browser every run here:
			iTunesConnectInterface iTunes = new iTunesConnectInterface( mybrowser );
			JSONObject itcData = iTunes.getAllAppsRequest();
			
			JSONArray apps = itcData.getJSONObject("data").getJSONArray("summaries");
			System.out.println( "Apps: "+ String.valueOf( apps.length() ) );
			ArrayList<String> ids = new ArrayList<String>();
			for ( Object app : apps )
			{
				
				//System.out.println( app ); //all info
				//See the pending version's status, if any:
				if( ! ((JSONObject)app).getJSONArray("versionSets").getJSONObject(0).isNull("inFlightVersion") )
				{
					String prepStatus = ((JSONObject)app).getJSONArray("versionSets").getJSONObject(0).getJSONObject("inFlightVersion").getString("state");
					//if( prepStatus.equals("pendingDeveloperRelease") )
					//{
						System.out.println(prepStatus);
						System.out.println( ((JSONObject)app).getString("name") );
						System.out.println( ((JSONObject)app).getString("bundleId") );
						ids.add( ((JSONObject)app).getString("bundleId") );
						System.out.println( "https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/" + ((JSONObject)app).getString("adamId") );
						System.out.println( " " );
					//}
					if( prepStatus.equals("prepareForUpload") && 
						!((JSONObject)app).getString("name").equals("CrossTown Fellowship") &&
						!((JSONObject)app).getString("name").contains("Worship Leader"))
					{
						/* Set inherit hires image upload:
						 */
						ProcessBuilder clearScreenshots = new ProcessBuilder( "ClearScreenshots.rb", 
								((JSONObject)app).getString("bundleId") );
						clearScreenshots.redirectOutput(ProcessBuilder.Redirect.INHERIT); //output the output.
						if (0 != clearScreenshots.start().waitFor())
						{
							System.err.println("Clear screenshots for update failed - see https://github.com/fastlane/fastlane/issues/1529");
							System.err.println("If you have not set the path, you must run:");
							System.err.println("sudo ln -s ~/Documents/Church_Apps/deployment/ClearScreenshots.rb /usr/local/bin/ClearScreenshots.rb");
							System.err.println("sudo chmod +x /usr/local/bin/ClearScreenshots.rb");
						} else {
							System.out.println("Screenshots should be set to inherit now.");
						}
						
						try
						{
							ProcessBuilder deliver = new ProcessBuilder("fastlane", "deliver", 
								"submit_build", "-u", "appdev@sharefaith.com",
								//Due to a bug in how it handles versions (https://github.com/fastlane/fastlane/issues/5271)
								//Need to specify the version eg app_version "2.0" in Deliverfile in working dir.
								"--skip_metadata", "--skip_binary_upload", "--skip_screenshots",
								"--submit_for_review",  "-a", ((JSONObject)app).getString("bundleId") );
							deliver.environment().put("FASTLANE_PASSWORD", iTunes.PWD);
							deliver.redirectOutput(ProcessBuilder.Redirect.INHERIT); //output the output.
							if (0 != deliver.start().waitFor())
							{
								System.err.println("Finalize fail");
							} else {
								System.out.println("Successfully submitted?");
								AppserveRecorder.recordBuildCompleted( ((JSONObject)app).getString("bundleId")
									.replace("com.sharefaith.churchapp.", "") );
							}
						}
						catch ( InterruptedException e )
						{
							System.err.println("Ok, skipping...");
						}
						//Remove generated ./screenshots
						//Note that rmdir doesn't do anything if dir has files:
						new ProcessBuilder( "rmdir", "./screenshots/" ).start().waitFor();
					}
				}
			}
			
			//HashMap<Integer,String> apps = AppserveRecorder.getRecords( AppserveRecorder.STATUS_BUILD_UPLOADED );
			/*for ( Integer k : apps.keySet())
			{
				System.out.println( String.valueOf(k) + ":" + apps.get(k) );
				ProcessBuilder deliver = new ProcessBuilder("fastlane", "deliver", 
					"submit_build", "-u", "appdev@sharefaith.com",
					"--skip_metadata", "--skip_binary_upload", "--skip_screenshots",
					"--submit_for_review",  "-a", "com.sharefaith.churchapp."+apps.get(k) );
				deliver.environment().put("FASTLANE_PASSWORD", "app$SF15!");
				deliver.redirectOutput(ProcessBuilder.Redirect.INHERIT); //output the output.
				//Note you MUST have the Deliverfile in the working directory!
				if (0 != deliver.start().waitFor())
				{
					System.err.println("Finalize fail");
				} else {
					System.out.println("Successfully submitted?");
					AppserveRecorder.recordBuildCompleted( apps.get(k) );
				}
				
			}
			System.out.println(String.valueOf(apps.size()) + " checked.");*/
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			nonworking.close();
		}
		
	}

}
