import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Set;

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

public class MainReleaser {

	public static void main(String[] args) throws IOException
	{
		System.out.println("This doesn't actually release... just prints out info");
		
		FirefoxProfile noCheck = new FirefoxProfile();
		//Work in Firefox 43+:
		noCheck.setPreference("xpinstall.signatures.required", false);
		FirefoxDriver mybrowser = new FirefoxDriver( noCheck );
		
		iTunesConnectInterface iTunes = new iTunesConnectInterface( mybrowser );
		//With logged in iTunesconnect, should have all the cookies to make requests.
		//Fastlane spaceship would possibly do this but is very very inefficient.
		
		//Instead, make direct request with cookies that the page would do - 200 status means ok, logged in:
		Set<Cookie> cookies = iTunes.browser.manage().getCookies();
		StringBuilder cookiestr = new StringBuilder();
		boolean first = true;
		for ( Cookie c : cookies)
		{
			if (c.getDomain().indexOf("apple.com") >= 0)
			{
				if (!first)
				{
					cookiestr.append("; ");
				}
				cookiestr.append( c.getName()+"="+c.getValue() );
				first = false;
			} else {
				System.out.println(c.getName()+"="+c.getValue());
			}
		}
	
		//User-only-request from app listing here:
		//URL myUrl = new URL("https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/services/universalPurchaseServices");
		//TODO this should be quicker than using the frontpage.
		URL myUrl = new URL("https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/apps/manageyourapps/summary/v2");
		
		HttpURLConnection urlConn = (HttpURLConnection)myUrl.openConnection();
		urlConn.setConnectTimeout( 60* 1000 );
		urlConn.setRequestProperty("Cookie", cookiestr.toString());
		System.out.println(cookiestr.toString());
		urlConn.setRequestProperty("Accept-Language","en-US,en;q=0.5");
		urlConn.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Gecko/20100101 Firefox/37.0");
		urlConn.connect();
		int code = urlConn.getResponseCode();
		if (code == 200)
		{
			BufferedReader br = new BufferedReader(new InputStreamReader((urlConn.getInputStream())));
			StringBuilder sb = new StringBuilder();
			String output;
			while ((output = br.readLine()) != null)
			{
				sb.append(output);
			}
			//Now we have the output (the json at that url)
			// Hint:
			//  python -m json.tool ./v2.json
			//  is good way to prettyprint these.
			JSONObject itcData = new JSONObject( sb.toString() );
			JSONArray apps = itcData.getJSONObject("data").getJSONArray("summaries");
			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") );
						String googleUrl = ((JSONObject)app).getString("bundleId").replace("com.sharefaith.churchapp.","https://play.google.com/store/apps/details?id=com.sharefaith.sfchurchapp_");
						
						//Check Google:
						HttpURLConnection gCheck = (HttpURLConnection)(new URL(googleUrl)).openConnection();
						gCheck.setRequestProperty("Accept-Language","en-US,en;q=0.5");
						gCheck.setRequestProperty("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.10; rv:37.0) Gecko/20100101 Firefox/37.0");
						gCheck.connect();
						int responseCode = gCheck.getResponseCode();
						
						System.out.println( String.valueOf( responseCode ) + ": " + googleUrl );
						System.out.println( " " );
					}
				}
				
			}
			
			System.out.println( "^ Those are the pending... to see what they are in our system use: \n");
			System.out.print( "SELECT * FROM sfappserve.Apps where uaid in (" );
			for ( int i=0; i < ids.size(); i++)
			{
				System.out.print("'");
				System.out.print( ids.get(i) );
				System.out.print("'");
				if( i+1 < ids.size() ) System.out.print(",");
			}
			System.out.print( ")" );
		} else {
			System.err.println("Not logged in?");
		}
		
	}

}
