package com.example.stockprophit;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;

@SuppressLint("NewApi")
public class DisplayMessageActivity extends Activity 
{
	private int NUMBER_OF_STOCKS = 12;
	public int flag[] = new int[NUMBER_OF_STOCKS];
    public Map<Object, String> ticker = new HashMap<Object, String>();
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_display_message);
		// Show the Up button in the action bar.
		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		Intent intent = getIntent();
		String key = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
        this.integrationTest(key);
		
		this.createHashMap();
        
		TextView textView = (TextView) findViewById(R.id.ticker_id);
		textView.setTextSize(20);
		
		String message = "";
		
		message = ticker.get(key);
		if(ticker.containsKey(key))
		{
			String stockdata[] = message.split(":");
			textView.setText(stockdata[0]);
			textView = (TextView) findViewById(R.id.prices_id);
			textView.setText(stockdata[1]);
			
			int check_int = Integer.parseInt(stockdata[2]);
			
			String ret = "";
	        
	        try {
	            InputStream inputStream = openFileInput("faves.txt");
	             
	            if ( inputStream != null ) {
	                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
	                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
	                ret = bufferedReader.readLine();
	                inputStream.close();
	                bufferedReader.close();
	            }
	        }
	        catch (FileNotFoundException e) {
	            Log.e(SocialActivity.class.getName(), "File not found: " + e.toString());
	        } 
	        catch (IOException e) {
	            Log.e(SocialActivity.class.getName(), "Can not read file: " + e.toString());
	        }
	        
	        ret = ret.replace(",", "").replace("[", "").replace("]", "").replace(" ", "");
	        Log.v("myapp", ret);	
	        for(int i = 0; i < ret.length(); i++)
	        {
	        	flag[i] = Integer.parseInt(Character.toString(ret.charAt(i)));
	        }
	        CheckBox cb = (CheckBox) findViewById(R.id.chk_fave);
			if(flag[check_int] == 1)
			{
				cb.setChecked(true);
			}
			else
			{
				cb.setChecked(false);
			}
		}
		else
		{
			textView.setText("Stock Not Found: " + key);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) 
	{
		switch (item.getItemId()) 
		{
		case android.R.id.home:
			// This ID represents the Home or Up button. In the case of this
			// activity, the Up button is shown. Use NavUtils to allow users
			// to navigate up one level in the application structure. For
			// more details, see the Navigation pattern on Android Design:
			//
			// http://developer.android.com/design/patterns/navigation.html#up-vs-back
			//
			NavUtils.navigateUpFromSameTask(this);
			return true;
		}
		return super.onOptionsItemSelected(item);
	}
	
	public void toggleFave(View view)
	{
		CheckBox cb = (CheckBox) findViewById(R.id.chk_fave);
		boolean checked = ((CheckBox) view).isChecked();
		
		if(checked)
		{
			TextView tv = (TextView) findViewById(R.id.ticker_id);
			String message = (String) tv.getText();
			message = ticker.get(message); 
			String stockdata[] = message.split(":");
			int index = Integer.parseInt(stockdata[2]);
			flag[index] = 1;
			try {
	    		FileOutputStream fos = openFileOutput("faves.txt", Context.MODE_WORLD_WRITEABLE);
	    		OutputStreamWriter osw = new OutputStreamWriter(fos);
	    		BufferedWriter bf = new BufferedWriter(osw);
	    		bf.write(Arrays.toString(flag));
	    		Log.v("myapp", Arrays.toString(flag));
	    		bf.close();
	    		osw.close();
	    		fos.close();
	    	} 
	    	catch (Exception e) {
	    		Log.v("myapp", "EXCEPTION CHECKED = TRUE");
	    	}
		}
		else
		{
			TextView tv = (TextView) findViewById(R.id.ticker_id);
			String message = (String) tv.getText();
			message = ticker.get(message); 
			String stockdata[] = message.split(":");
			int index = Integer.parseInt(stockdata[2]);
			flag[index] = 0;
			try {
	    		FileOutputStream fos = openFileOutput("faves.txt", Context.MODE_WORLD_WRITEABLE);
	    		OutputStreamWriter osw = new OutputStreamWriter(fos);
	    		BufferedWriter bf = new BufferedWriter(osw);
	    		bf.write(Arrays.toString(flag));
	    		Log.v("myapp", Arrays.toString(flag));
	    		bf.close();
	    		osw.close();	
	    		fos.close();
	    	} 
	    	catch (Exception e) {
	    		Log.v("myapp", "EXCEPTION CHECKED = FALSE");
	    	}

		}
	}
	
	private void createHashMap()
	{
        ticker.put(new String("AAPL"), "AAPL:442.66:0");
        ticker.put(new String("Apple"), "AAPL:442.66:0");
        ticker.put(new String("AAPL Apple Inc."), "AAPL:442.66:0");  
        
        ticker.put(new String("BAC"), "BAC:12.18:1");  
        ticker.put(new String("Bank of America"), "BAC:12.18:1");  
        ticker.put(new String("BAC Bank of America"), "BAC:12.18:1");  
        
        ticker.put(new String("BRK.A"), "BRK.A:156280.00:2");  
        ticker.put(new String("Berkshire Hathaway"), "BRK.A:156280.00:2");  
        ticker.put(new String("BRK.A Berkshire Hathaway"), "BRK.A:156280.00:2");  
        
        ticker.put(new String("GOOG"), "GOOG:794.19:3");
        ticker.put(new String("Google"), "GOOG:794.19:3");
        ticker.put(new String("GOOG Google Inc."), "GOOG:794.19:3");
        
        ticker.put(new String("HPQ"), "HPQ:23.84:4");  
        ticker.put(new String("Hewlett-Packard"), "HPQ:23.84:4");  
        ticker.put(new String("HPQ Hewlett-Packard"), "HPQ:23.84:4");  
        
        ticker.put(new String("INTC"), "INTC:21.83:5");  
        ticker.put(new String("Intel"), "INTC:21.83:5");  
        ticker.put(new String("INTC Intel"), "INTC:21.83:5");
        
        ticker.put(new String("KO"), "KO:40.44:6");  
        ticker.put(new String("Coca-Cola Company"), "KO:40.44:6");  
        ticker.put(new String("KO Coca-Cola Company"), "KO:40.44:6");
        
        ticker.put(new String("MMM"), "MMM:106.31:7");  
        ticker.put(new String("3M"), "MMM:106.31:7");  
        ticker.put(new String("MMM 3M"), "MMM:106.31:7");
        
        ticker.put(new String("MSFT"), "MSFT:28.60:8");  
        ticker.put(new String("Microsoft"), "MSFT:28.60:8");  
        ticker.put(new String("MSFT Microsoft"), "MSFT:28.60:8");
        
        ticker.put(new String("TGT"), "TGT:68.45:9");  
        ticker.put(new String("Target"), "TGT:68.45:9");  
        ticker.put(new String("TGT Target Corporation"), "TGT:68.45:9");  
        
        ticker.put(new String("TXN"), "TXN:35.48:10");  
        ticker.put(new String("Texas Instruments"), "TXN:35.48:10");  
        ticker.put(new String("TGT Target Corporation"), "TXN:35.48:10");
        
        ticker.put(new String("WMT"), "WMT:74.83:11");
        ticker.put(new String("Walmart"), "WMT:74.83:11");
        ticker.put(new String("WMT Walmart"), "WMT:74.83:11");
	}
	
	private void testValidTicker(String tick)
	{
		// Test that a valid ticker symbol or company name is passed to the activity
		assert ticker.containsKey(tick);
	}
	
	private void testValidFlag()
	{
		//Test after reading in, the flag array contains a string of 12 characters, 0s or 1s (000000000000 default)
		assert flag[0] == 0 || flag[0] == 1;
		assert flag[NUMBER_OF_STOCKS - 1] == 0 || flag[NUMBER_OF_STOCKS - 1] == 1;
	}
    private void testFile()
    {
    	//Test if the file to read exists 
    	File f = new File("posts.txt");
    	assert f.exists();
    	//Test if the faves file exists (Contains 1 line array of 12 zeros and ones)
    	//Stored as [1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 1] then parsed to 110100000001
    	File g = new File("faves.txt");
    	assert g.exists();
    }
    private void integrationTest(String tick)
    {
    	this.testValidTicker(tick);
    	this.testValidFlag();
    	this.testFile();
    }
}
