  // written by:Frank Bohn
  // tested by:Frank Bohn
  // debugged by:Frank Bohn

package com.example.stockprophit;

import java.io.BufferedReader;
import java.io.BufferedWriter;
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.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.QuickContactBadge;
import android.widget.TextView;
import android.support.v4.app.NavUtils;

public class FriendProfile_Activity extends Activity {
	
	
	private int NUMBER_OF_USERS = 6;
	public int flag[] = new int[NUMBER_OF_USERS];
    public Map<Object, String> hashy = new HashMap<Object, String>();
    public Map<String, Integer> hashpics = new HashMap<String, Integer>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_friend_profile_); //Creates the page using activity_friend_profile template
		// Show the Up button in the action bar.
		getActionBar().setDisplayHomeAsUpEnabled(true);
		
		Intent intent = getIntent();
		String key = intent.getStringExtra(FollowingActivity.EXTRA_MESSAGE3);
		
				
		this.createHashMap();
		//Get the user name from shared preferences to use as name 
		TextView tv = (TextView) findViewById(R.id.name_text); 
		SharedPreferences s = getSharedPreferences("prefs", 1);
		String name = s.getString("searchname", "NONAME");
		String test = s.getString("username", "NOUSERNAME");
		
		if(key != null){
			if(hashy.containsKey(key))
			{
				name=key;
			}
		}
		
		if(hashpics.containsKey(name))
		{
			QuickContactBadge qb = (QuickContactBadge) findViewById(R.id.quickContactBadge1);
			qb.setImageResource((int) hashpics.get(name));
		}
		
		CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);
		if(test.equals(name)){
			cb.setVisibility(View.GONE);
		}
		
		List<String> abc = new ArrayList<String>();
        
		String username = name + ".txt"; //create a string to use for file name
		
		
        try {
            InputStream inputStream = openFileInput(username); //open file
             
            if ( inputStream != null ) {
            	//read strings in the file
                InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                String receiveString = ""; 
                
                
                while ( (receiveString = bufferedReader.readLine()) != null ) {
                	abc.add(receiveString);	// save the strings from file to a string variable
                }
                inputStream.close();
                bufferedReader.close();
            }
        }
        
        catch (FileNotFoundException e) { //catch exception
            Log.e(SocialActivity.class.getName(), "File not found: " + e.toString());
        } 
        catch (IOException e) { //catch exception
            Log.e(SocialActivity.class.getName(), "Can not read file: " + e.toString());
        }
        
        Collections.reverse(abc); // reverse string so that more recent posts at top
        
        //Use adapter to populate the listview with the string
        ArrayAdapter<String> nfadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, abc);
        ListView listview = (ListView) findViewById(R.id.user_recentpost);
        listview.setAdapter(nfadapter);
        
		//Create TextView object and set text size to 20
		//TextView textView = (TextView) findViewById(R.id.name_text);
		//textView.setTextSize(20);
		String message = "";
		
		//Get message from the homescreen edittext box
		//Intent intent = getIntent();
		//String key = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
		
				
		//Get string from hashmap with the key as the string from the received EditText
		message = hashy.get(name);
		
		//Check that the key is contained within 
		if(hashy.containsKey(name)){
			String followingdata[] = message.split(":");
			tv.setText(followingdata[0]);
			tv = (TextView) findViewById(R.id.bio_text);
			tv.setText(followingdata[1]);
			
			
			int check_int = Integer.parseInt(followingdata[2]);
			
			String ret = "";
	        
	        try {
	        	SharedPreferences sss = getSharedPreferences("prefs", 1);
				String n = sss.getString("username", "NONAME");
				String followingfile = n + "following.txt"; //use user name to get file name
	            InputStream inputStream = openFileInput(followingfile); //open following.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("myfollowing", ret);	
	        for(int i = 0; i < ret.length(); i++)
	        {
	        	flag[i] = Integer.parseInt(Character.toString(ret.charAt(i)));
	        }
			if(flag[check_int] == 1)
			{
				cb.setChecked(true);
			}
			else
			{
				cb.setChecked(false);
			}
		}
		//else
		//{
		//	tv.setText("User Not Found: " + name);
		//}	        
	}

	

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_friend_profile_, menu);
		return true;
	}

	@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 toggleFollowing(View view)
	{
		CheckBox cb = (CheckBox) findViewById(R.id.checkBox1);
		boolean checked = ((CheckBox) view).isChecked();
		
		if(checked)
		{

			SharedPreferences s = getSharedPreferences("prefs", 1);
			String n = s.getString("username", "NONAME");
			String followingfile = n + "following.txt"; //use user name to get file name
		    
	    			
			TextView tv = (TextView) findViewById(R.id.name_text);
			String message = (String) tv.getText();
			message = hashy.get(message); 
			String followingdata[] = message.split(":");
			int index = Integer.parseInt(followingdata[2]);
			flag[index] = 1;
			try {
	    		FileOutputStream fos = openFileOutput(followingfile, Context.MODE_WORLD_WRITEABLE);
	    		OutputStreamWriter osw = new OutputStreamWriter(fos);
	    		BufferedWriter bf = new BufferedWriter(osw);
	    		bf.write(Arrays.toString(flag));
	    		Log.v("myfollowing", Arrays.toString(flag));
	    		bf.close();
	    		osw.close();
	    		fos.close();
	    	} 
	    	catch (Exception e) {
	    		Log.v("myfollowing", "EXCEPTION CHECKED = TRUE");
	    	}
		}
		else
		{
			SharedPreferences s = getSharedPreferences("prefs", 1);
			String n = s.getString("username", "NONAME");
			String followingfile = n + "following.txt"; //use user name to get file name
			
			TextView tv = (TextView) findViewById(R.id.name_text); 
			String message = (String) tv.getText();
			message = hashy.get(message); 
			String followingdata[] = message.split(":");
			int index = Integer.parseInt(followingdata[2]);
			flag[index] = 0;
			try {
	    		FileOutputStream fos = openFileOutput(followingfile, Context.MODE_WORLD_WRITEABLE);
	    		OutputStreamWriter osw = new OutputStreamWriter(fos);
	    		BufferedWriter bf = new BufferedWriter(osw);
	    		bf.write(Arrays.toString(flag));
	    		Log.v("myfollowing", Arrays.toString(flag));
	    		bf.close();
	    		osw.close();	
	    		fos.close();
	    	} 
	    	catch (Exception e) {
	    		Log.v("myfollowing", "EXCEPTION CHECKED = FALSE");
	    	}
		}
	}
	private void createHashMap()
	{
		//Put ticker symbols and company names in the hash map
        hashy.put(new String("FrankBohn"), "FrankBohn:Student:0");
        hashy.put(new String("EricLee"), "EricLee:Student:1");
        hashy.put(new String("GioDegrande"), "GioDegrande:Student:2");
        hashy.put(new String("AsimAlvi"), "AsimAlvi:Student:3");
        hashy.put(new String("SangitPatel"), "SangitPatel:Student:4");
        hashy.put(new String("AndrewDemoleas"), "AndrewDemoleas:Student:5");
        hashpics.put("FrankBohn", 2130837507);
        hashpics.put("AsimAlvi", 2130837504); 
        hashpics.put("SangitPatel", 2130837513);
        hashpics.put("GioDegrande", 2130837509);
        hashpics.put("EricLee", 2130837507);
        hashpics.put("AndrewDemoleas", 2130837507);
	}
}
