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

/**
 * Somewhat redundant since we can check prep status... this sends markSubmitted to appserve too
 * @author sharefaith2
 *
 */
public class AppserveRecorder
{
	//Must match in appserve.sharefaith.com/classes/app/ItcCollector.php
	
	public final static int STATUS_OTHER = 0;
	public final static int STATUS_BUILD_UPLOADED = 1;
	public final static int STATUS_BUILD_READY = 2;
	public final static int STATUS_BUILD_COMPLETE = 3;
	public final static int STATUS_BUILD_REJECTED = 4;
	
	public final static int STATUS_BUILD_LOCAL_STARTED = 5;
	public final static int STATUS_BUILD_LOCAL_FINISHED = 6;
	
	//Same as in Google.
	public final static String FINALIZE_NOTIFICATION_URL = "https://appserve.sharefaith.com/server.php?action=markAppSubmitted";
	
	private static void recordStatus( int appid, int buildStatus )
	{
		AppserveRecorder.recordStatus( String.valueOf(appid), buildStatus );
	}

	/**
	 * Takes int (or possibly short id like 0220fdaf9)
	 * @param appid identifier
	 * @param buildStatus constant
	 */
	private static void recordStatus( String appid, int buildStatus )
	{
		URL myUrl = null;
		try
		{
			myUrl = new URL("https://appserve.sharefaith.com/server.php?action=recordItc&a=" + ( appid ) + "&c=" + String.valueOf( buildStatus ));
		} catch (MalformedURLException e2)
		{
			e2.printStackTrace();
		}
	
		try
		{
			HttpURLConnection urlConn = (HttpURLConnection)myUrl.openConnection();
			urlConn.setConnectTimeout( 60* 1000 );
			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/41.0");
			urlConn.connect();
			int code = urlConn.getResponseCode();
			if (code == 200)
			{
				//pass
			} else {
				System.out.println( "Received code "+code);
				try
				{
					Thread.sleep( 50* 1000 );
				} catch (InterruptedException e)
				{
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				AppserveRecorder.recordStatus( appid, buildStatus );
			}
		} catch (IOException e1)
		{
			try
			{
				Thread.sleep( 50* 1000 );
			} catch (InterruptedException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			AppserveRecorder.recordStatus( appid, buildStatus );
		}
		
		
		try
		{
			String addr = FINALIZE_NOTIFICATION_URL + "&uaid=" + appid + "&platform=ios";
			System.out.println( "FINALIZING REQUEST WITH: " + addr );
			URL url = new URL( addr );
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();
			connection.setRequestMethod( "GET" );
			StringBuilder result = new StringBuilder();
			BufferedReader rd = new BufferedReader( new InputStreamReader( connection.getInputStream() ) );
			String line;
			while( ( line = rd.readLine() ) != null ) 
			{
			   result.append( line );
			}
			rd.close();
		}
		catch( Exception e )
		{
			e.printStackTrace();
			System.err.println( "FAILED MARKING UPDATE COMPLETE" );
		}
	}
	
	public static void recordBuildStarted( int appid )
	{
		AppserveRecorder.recordStatus( appid, STATUS_BUILD_LOCAL_STARTED );
	}
	
	public static void recordReadyUploaded( int appid )
	{
		AppserveRecorder.recordStatus( appid, STATUS_BUILD_UPLOADED );
	}
	
	public static void recordBuildCompleted( int appid )
	{
		AppserveRecorder.recordStatus( appid, STATUS_BUILD_COMPLETE );
	}
	
	/**
	 * Theoretically the only one that need string as the finalizer gets hex string from appserve.
	 * @param appid
	 */
	public static void recordBuildCompleted( String appid )
	{
		AppserveRecorder.recordStatus( appid, STATUS_BUILD_COMPLETE );
	}
	
	public static HashMap<Integer,String> getRecords( int status ) throws IOException
	{
		//TODO grab, decode.
		URL myUrl = null;
		try
		{
			myUrl = new URL("https://appserve.sharefaith.com/server.php?action=itcStatusAllForCode&c=" + String.valueOf( status ) );
		} catch (MalformedURLException e2)
		{
			e2.printStackTrace();
		}
		HttpURLConnection urlConn = (HttpURLConnection)myUrl.openConnection();
		urlConn.setConnectTimeout( 60* 1000 );
		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/41.0");
		urlConn.connect();
		int code = urlConn.getResponseCode();
		if (code == 200)
		{
			BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
			StringBuilder lines = new StringBuilder();
			String inputLine;
	        while (( inputLine = in.readLine() ) != null) 
	        {
	        	lines.append( inputLine );
	        }
	        in.close();
	        SerializedPhpParser parser = new SerializedPhpParser( lines.toString()
	        		//why mix xml with phpserialize?!
	        		.replace("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>	<root>", "")
	        		.replace("	</root>", ""));
	        return (HashMap<Integer, String>) parser.parse();
		} else {
			throw new IOException( "Appserve read network error code "+String.valueOf( code ) );
		}
	}
}
