import java.io.File;
import java.util.List;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;


public class PushServeInterface extends SFSeleniumBase {
	
	public final String PUSHSERVE_URL = "https://pushserve.sharefaith.com/users/login";
	public final String PUSHSERVE_USER = "appdev@sharefaith.com";
	public final String PUSHSERVE_PASS = "app$SF15!";
	
	public final String PUSHSERVE_MANAGE_URL = "https://pushserve.sharefaith.com/apps/manage-apps";


	public final String PUSH_LOGIN_SELECTOR = "//input[contains(@type,'text') and contains(@name,'email')]";
	public final String PUSH_PASSWORD_SELECTOR = "//input[contains(@type,'password') and contains(@name,'password')]";
	public final String PUSH_LOGIN_BTN_SELECTOR = "//button[contains(text(),'Sign In')]";
	
	public final String PUSH_TABLE_HEADER_SELECTOR = "//th[contains(text(),'Apple App Name')]";
	public final String PUSH_SEARCH_RESULT_SELECTOR = "a[href^='https://pushserve.sharefaith.com/apps/edit-app/']";
	public final String PUSH_APP_NAME_SELECTOR = "//input[contains(@type,'text') and contains(@id,'android_app_name')]";
	public final String PUSH_BUNDLE_ID_SELECTOR = "//input[contains(@type,'text') and contains(@id,'android_app_id')]";
	public final String PUSH_API_KEY_SELECTOR = "//input[contains(@type,'text') and contains(@id,'gcm_api_key')]";
	public final String PUSH_SAVE_BTN_SELECTOR = "//button[contains(@type,'submit') and contains(text(),'Save')]";
	public final String PUSH_SUCCESS_SELECTOR = "//div[contains(@class,'alert-success')]";
	private boolean pushserveLoggedIn;
	
	public PushServeInterface(WebDriver existingdriver)
	{
		this.browser = existingdriver;
		this.pushserveLoggedIn = false;
	}
	
	// Login to pushserve if we're not already logged in
	public void pushserveLogin() throws Exception
	{
		if( this.pushserveLoggedIn )
		{
			return;
		}
		
		browser.get( PUSHSERVE_URL );
		this.waitForXpath( PUSH_LOGIN_SELECTOR );
		
		try
		{
			WebElement loginInput = this.qXpath( PUSH_LOGIN_SELECTOR );
			WebElement passwordInput = this.qXpath( PUSH_PASSWORD_SELECTOR );
			WebElement submitBtn = this.qXpath( PUSH_LOGIN_BTN_SELECTOR );
			
			loginInput.click();
			loginInput.sendKeys( PUSHSERVE_USER );
			
			passwordInput.click();
			passwordInput.sendKeys( PUSHSERVE_PASS );
			
			submitBtn.click();
		}
		catch( Exception e )
		{
			e.printStackTrace();
			throw new Exception( "Could not login to pushserve" );
		}
		
		this.pushserveLoggedIn = true;
	}
	
	// Setups push notifications with pushserve. Will fail if the app hasn't already been added for iOS
	public void setupPush( AppData data, String GCMKEY ) throws Exception
	{
		String bundleId = data.getId();
		
		// handle cases in which pushserve logs out.
		browser.get( PUSHSERVE_MANAGE_URL + "?q=" + bundleId );
		boolean found = this.waitForXpath( PUSH_TABLE_HEADER_SELECTOR, 15 );
		
		// we've been logged out
		if( !found )
		{
			this.pushserveLoggedIn = false;
			this.pushserveLogin();
			
			this.setupPush( data, GCMKEY );
			return;
		}
		
		try
		{
			List<WebElement> searchResults = this.qAll( PUSH_SEARCH_RESULT_SELECTOR );
			if( searchResults.size() != 1 )
			{
				throw new Exception( "I got the wrong number of search results: " + searchResults.size() );
			}
			searchResults.get( 0 ).click();
		}
		catch( Exception e )
		{
			e.printStackTrace();
			throw new Exception( "Could not find any search results" );
		}
		this.waitForXpath( PUSH_APP_NAME_SELECTOR );
		
		try
		{
			WebElement nameInput = this.qXpath( PUSH_APP_NAME_SELECTOR );
			WebElement idInput = this.qXpath( PUSH_BUNDLE_ID_SELECTOR );
			WebElement apiInput = this.qXpath( PUSH_API_KEY_SELECTOR );
			WebElement saveBtn = this.qXpath( PUSH_SAVE_BTN_SELECTOR );
			
			nameInput.clear();
			nameInput.sendKeys( data.getTitle() );
			
			idInput.clear();
			idInput.sendKeys( data.getAndroID() );
			
			apiInput.clear();
			apiInput.sendKeys( GCMKEY );
			
			saveBtn.click();
		}
		catch( Exception e )
		{
			e.printStackTrace();
			throw new Exception( "Could not save complete Android pushserve actions" );
		}
		// Make sure there was a success message before moving on with our lives
		this.waitForXpath( PUSH_SUCCESS_SELECTOR );
		
	}
	
	public void addIOSApp(AppData data) throws Exception
	{
		File pk12 = new File( data.getDataDir().getParentFile(), "Certificates.p12" );
		if( !pk12.exists())
		{
			throw new Exception("Certificates.p12 not created yet");
		}
			
		this.browser.get("http://pushserve.sharefaith.com/apps/new-app");
		this.q("#apple_app_name").sendKeys(data.getTitle());
		this.q("#apple_app_id").sendKeys(data.getId());
		this.q("#apple_apns_platform >[value=\"APNS\"]").click();
		this.q("[for=\"apns_cert\"] ~.fileupload input[type=file]").sendKeys( pk12.getAbsolutePath() );
		this.q("form[action*='/apps/update-app'] [type=submit]").click();
		this.waitFor("div.alert.alert-success");
	}
	
}
