package com.calculator.test;

import android.content.Context;
import android.test.ActivityInstrumentationTestCase2;
import com.calculator.Main;
import com.jayway.android.robotium.solo.Solo;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;
import jxl.read.biff.BiffException;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;

public class RobotiumTests_DataDriven extends
		ActivityInstrumentationTestCase2<Main> {

	private Solo solo;

	Workbook wb;
	WritableWorkbook copy;
	WritableSheet sheet;
	Boolean FuntionResult = false;
	Cell rowData[] = null;
	private String[] FirstValue;
	private String[] SecondValue;
	int rowCount = 0;
	WorkbookSettings ws = null;
	Workbook workbook = null;
	Sheet s = null;
	String[] TestResults;

	public RobotiumTests_DataDriven() {
		super("com.calculator", Main.class);
	}

	@Override
	protected void setUp() throws Exception {
		solo = new Solo(getInstrumentation(), getActivity());
	}

	public void CanOpenSettings() {
		solo.pressMenuItem(0);
	}

	public void testMultiplyResult() {
		getTestDataFile();
		TestResults = new String[rowCount];
		
			for (int i = 1; i < rowCount; i ++ )
			{
				solo.enterText(0, FirstValue[i].toString());
				solo.enterText(1, SecondValue[i].toString());
				solo.clickOnButton("Multiply");
				float First = Float.parseFloat(FirstValue[i].toString());
				float Second = Float.parseFloat(SecondValue[i].toString());
				float expectedResult = First*Second;
				float actualResult = Float.parseFloat(solo.getText(9).getText().toString());
				
				System.out.println("Value in Resultant Field "+solo.getText(9).getText().toString());
				System.out.println("Expected Value "+expectedResult);
				
				assertNotNull(solo.getText(9));
				assertEquals("Values are not same", expectedResult, actualResult); 
				TestResults[i] = "Pass";  
					
				solo.clearEditText(0);
				solo.clearEditText(1);
			}
			writeResults(TestResults);
		}

	public void readTestData(InputStream fileInputStream) throws Exception {
		ws = null;
		workbook = null;
		s = null;
		
		int columnCount = '0';
		int totalSheet = 0;
		String firstSheet = "TestCases";
		String secondSheet = "TestScenarios";

		try {
			ws = new WorkbookSettings();
			ws.setLocale(new Locale("en", "EN"));
			workbook = Workbook.getWorkbook(fileInputStream, ws);

			totalSheet = workbook.getNumberOfSheets();
			if(totalSheet > 0) {
				 
					if (!workbook.getSheet(0).getName().equals(firstSheet))
					{
						System.out.println ("contents are not fine");
					}
					
					if (!workbook.getSheet(1).getName().equals(secondSheet))
					{
						System.out.println ("contents are not fine");
					}			 
				}
			
			else 
				System.out.println ("There is not any sheet available.");
		
			s = workbook.getSheet(1);
			
			rowCount = s.getRows();
			FirstValue = new String[rowCount];
			SecondValue = new String[rowCount];
			
			columnCount = s.getColumns();
			rowData = s.getRow(0);

			if (rowData[0].getContents().length() != 0)
			{
				for (int i =1; i < rowCount; i ++)
				{
				
					rowData = s.getRow(i);
					
					if (rowData[5].getContents().equals("Yes"))
					{
						System.out.println("Executed: " + rowData[1].getContents());
						FirstValue[i] = rowData[2].getContents().toString();
						SecondValue[i] = rowData[3].getContents().toString();
					}
					else 
					{
						System.out.println("We will skip "+rowData[1].getContents());
					}
				}
				System.out.println("Success");

			}			
			workbook.close();			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		}
	}

	public void readTestDataCopy(InputStream fileInputStream) throws Exception {
		ws = null;
		workbook = null;
		s = null;
		
		int columnCount = '0';

		try {
			ws = new WorkbookSettings();
			ws.setLocale(new Locale("en", "EN"));
			workbook = Workbook.getWorkbook(fileInputStream, ws);

			s = workbook.getSheet(0);
			
			rowCount = s.getRows();
			FirstValue = new String[rowCount]; //First Value array size
			SecondValue = new String[rowCount];//Second Value array size
			
			columnCount = s.getColumns();
			rowData = s.getRow(0);

			if (rowData[0].getContents().length() != 0)
			{
				for (int i =1; i < rowCount; i ++)
				{
				
					rowData = s.getRow(i);
					
					System.out.println("Read: TestCase" + i);
						FirstValue[i] = rowData[1].getContents().toString();
						SecondValue[i] = rowData[2].getContents().toString();

				}
				System.out.println("Success");

			}			
			workbook.close();			
		} catch (IOException e) {
			e.printStackTrace();
		} catch (BiffException e) {
			e.printStackTrace();
		}
	}
	
	public void writeResults(String[] results) 
	{
		FileOutputStream outputStream = null;   
		
		try{
			outputStream = getActivity().openFileOutput("TestResultData.txt", Context.MODE_WORLD_READABLE);
			
			for (int i=0; i <results.length; i ++)
			{
			outputStream.write((results[1].toString()+"\n").getBytes());
			}
			
			}catch (IOException e) {
				e.printStackTrace();
			}finally {
					if (outputStream != null) {
		            try {
		                outputStream.flush();
		                outputStream.close();
		            } catch (IOException e) {
		            	e.printStackTrace();}
						}
			}
		}

	public void getTestDataFile()
	{
		 FileInputStream fs = null;
			try {	
				fs = getActivity().openFileInput("TestData.csv");
				readTestDataCopy(fs);
				
			} catch (IOException e) {
				e.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
			finally {
				try {
					fs.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}	
	}

	@Override	
	public void	tearDown() throws Exception	
	  {	
		try	
			{	
			solo.finalize();	
			}	
	  catch	(Throwable	e)	
	  {	
		  e.printStackTrace();	
	  }	
	  	getActivity().finish();	
	  	super.tearDown();	
	  }
}