package com.java.example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ProtocolException;
import java.net.URL;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

public class O2Extra
{
	///////////////////////////////////////////////////////////////////////////////////////////////////////
	// Tato konstanta musi obsahovat vase telefonni cislo bez +420. Cislo musi byt registrovano na O2Extra.
    ///////////////////////////////////////////////////////////////////////////////////////////////////////
	static final String PHONE_NUMBER = "";
	
	static final String BASE_URL = "https://www.o2extra.cz/index.html";
	static final String LOGIN_URL = "https://corporatelogin.cz.o2.com/o2extra/login.html";
	
	static String cookie;
	static String flowExecutionKey;
	static String authorizationCode;
	static String location;
	
	public static void main(String[] args)
	{
		try {
			trustAllHosts();
			loadPhoneNumberPage();
			requestAuthorizationCodeSms();
			readAuthorizationCode();
			sendAuthorizationCode();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	static void loadPhoneNumberPage() throws IOException, ProtocolException
	{
		// create connection
		HttpsURLConnection connection = createConnection(LOGIN_URL + "?returnUrl=" + BASE_URL);
		connection.setRequestMethod("GET");
		connection.setRequestProperty("Referer", BASE_URL);
		
		connection.connect();
		
		// save cookie
		cookie = connection.getHeaderField("Set-Cookie");
		cookie = cookie.substring(0, cookie.indexOf(';'));
		
		// save flow execution key
		flowExecutionKey = readFlowExecutionKey(readConnectionInputStream(connection));
	}
	
	static void requestAuthorizationCodeSms() throws IOException, ProtocolException
	{
		// create connection
		HttpsURLConnection connection = createConnection(LOGIN_URL + ";" + cookie + "?returnUrl=" + BASE_URL);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestProperty("Cookie", cookie);
		connection.setRequestProperty("Referer", LOGIN_URL + "?returnUrl=" + BASE_URL);
		
		// add post data
		connection.setDoOutput(true);
		String postData = "phoneNumber=" + PHONE_NUMBER + "&_email=on&_flowExecutionKey=" + flowExecutionKey + "&dueToIEBug=1&_eventId_submit.x=0&_eventId_submit.y=0";
		OutputStream stream = connection.getOutputStream();
		stream.write(postData.getBytes());
		stream.close();
		
		connection.connect();
		
		// cookie is same, we don't have to save it again
		
		// save flow execution key
		flowExecutionKey = readFlowExecutionKey(readConnectionInputStream(connection));
	}
	
	static void readAuthorizationCode() throws IOException
	{
		System.out.println("Insert authorization code:");
		
		// read one line from terminal
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
	    authorizationCode = reader.readLine();
	    reader.close();
	}
	
	static void sendAuthorizationCode() throws IOException, ProtocolException
	{
		// create connection
		HttpsURLConnection connection = createConnection(LOGIN_URL + "?returnUrl=" + BASE_URL);
		connection.setRequestMethod("POST");
		connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		connection.setRequestProperty("Cookie", cookie);
		connection.setRequestProperty("Referer", LOGIN_URL + ";" + cookie + "?returnUrl=" + BASE_URL);
		
		// add post data
		connection.setDoOutput(true);
		String postData = "otp=" + authorizationCode + "&_eventId_submit.x=0&_eventId_submit.y=0&dueToIE=1&_flowExecutionKey=" + flowExecutionKey;
		OutputStream stream = connection.getOutputStream();
		stream.write(postData.getBytes());
		
		connection.connect();
		
		// save relocation address
		location = connection.getHeaderField("Location");
		
		/////////////////////////////////////////////////////////////////////////////
		// Tady dojde k chybe, location je null a odpoved serveru vypada uplne jinak.
		/////////////////////////////////////////////////////////////////////////////
		
//		String m = connection.getResponseMessage();
//		Map<String, List<String>> h = connection.getHeaderFields();
//		String r = readConnectionInputStream(connection);
	}
	
	static HttpsURLConnection createConnection(String urlString) throws IOException
	{
		// create connection
        URL url = new URL(urlString);
        HttpsURLConnection connection = (HttpsURLConnection)url.openConnection();
        
        // set connection parameters
		connection.setHostnameVerifier(new TrustfulHostnameVerifier());
		connection.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		connection.setRequestProperty("Accept-Language", "cs,en-us;q=0.7,en;q=0.3");
		connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
		connection.setRequestProperty("Accept-Charset", "windows-1250,utf-8;q=0.7,*;q=0.7");
		connection.setRequestProperty("Connection", "keep-alive");
		connection.setRequestProperty("Host", "corporatelogin.cz.o2.com");
		connection.setRequestProperty("Keep-Alive", "115");
		connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; cs; rv:1.9.2.10) Gecko/20100914 Firefox/3.6.10");
		
		return connection;
	}
	
	static String readConnectionInputStream(HttpsURLConnection connection) throws IOException
	{
		StringBuilder builder = new StringBuilder();
		
		InputStream stream = connection.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
		for (String line; null != (line = reader.readLine()); ) {
			builder.append(line);
		}
		reader.close();
		
		return builder.toString();
	}
	
	static String readFlowExecutionKey(String response)
	{
		int index = response.indexOf("_flowExecutionKey") + 26;
		return response.substring(index, response.indexOf('"', index));
	}
	
	///////////////////////////
	// Zbytek kodu je prevzaty.
	///////////////////////////
	
	static void trustAllHosts()
    {
		// create a trust manager that does not validate certificate chains
		TrustManager[] trustAllCerts = new TrustManager[] { new TrustfulTrustManager() };

		// install the all-trusting trust manager
		try {
			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, trustAllCerts, new java.security.SecureRandom());
			HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
		} catch (Exception e) {
			e.printStackTrace();
		}
    }
	
	// host-name verifier that trusts all the host-names
	static class TrustfulHostnameVerifier implements HostnameVerifier
	{
		@Override
		public boolean verify(String hostname, SSLSession session)
		{
			return true;
		}	
	}
	
	// trust manager that doesn't validate certificate chains
	static class TrustfulTrustManager implements X509TrustManager
	{
		@Override
		public X509Certificate[] getAcceptedIssuers()
		{
			return new java.security.cert.X509Certificate[] {};
		}

		@Override
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException
		{
		}

		@Override
		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException
		{			
		}
	}
}