
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.JSONException;
import org.json.JSONObject;
import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxProfile;

public class MainListiOSPrepStatus
{

	public static void main(String[] args) throws Exception
	{
		PrintWriter nonworking = new PrintWriter("Notfinalized.txt", "UTF-8");
		try
		{
			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("rejected") && //("prepareForUpload") && 
						!((JSONObject)app).getString("name").equals("CrossTown Fellowship") &&
						!((JSONObject)app).getString("name").contains("Worship Leader"))
					{

						System.out.println( ((JSONObject)app).getString("bundleId") );
						try{
							System.out.println("Current app state:" + 
									((JSONObject)app).getJSONArray("versionSets").getJSONObject(0).getJSONObject("deliverableVersion").getString("state")
									);
						} catch( JSONException jex )
						{
							System.out.println("No deliverable currently.");
						}
						System.out.println("https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/app/" + ((JSONObject)app).getString("adamId"));
						System.out.println("-\n");
						
					}
				}
			}
			
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			nonworking.close();
		}
		
	}


}
