package com.example.lamano;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

/* Clase del Fragment que despliega una lista de amigos */
public class AmigosFragment extends Fragment{
	List<Map<String,String>> friendList = new ArrayList<Map<String,String>>();
	OnFriendSelectedListener mCallback;
	/* Interface que será implementada por HomeActivity, 
	  se llama cuando se selecciona un item de la lista */
	public interface OnFriendSelectedListener{
		public void onFriendSelected(String name);
	}
	
	
	@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        
        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnFriendSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnFriendSelectedListener");
        }
    }
	
	@Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View toreturn =  inflater.inflate(R.layout.amigos_view, container, false);
        
        initList();
        ListView lv = (ListView)toreturn.findViewById(R.id.friend_list);
        
        SimpleAdapter sa = new SimpleAdapter(this.getActivity(), friendList, 
        		R.layout.friend_list_row, new String[]{"nombre"}, new int[]{R.id.friend_list_name});
        lv.setAdapter(sa);
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        	public void onItemClick(AdapterView<?> parentAdapter, View view,
        			int position, long id){
        		TextView tv =(TextView)view.findViewById(R.id.friend_list_name);
        		String name = tv.getText().toString();
        		mCallback.onFriendSelected(name);
        	}
        });
        
        return toreturn;
	}
	/* Método que inicializa el xml con los datos */
	private void initList(){
		XmlPullParserFactory pullParserFactory;
		try {
			pullParserFactory = XmlPullParserFactory.newInstance();
			XmlPullParser parser = pullParserFactory.newPullParser();

			    InputStream in_s = this.getActivity().getApplicationContext().getAssets().open("frienddata.xml");
		        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
	            parser.setInput(in_s, null);

	            parseXML(parser);
	            in_s.close();

		} catch (XmlPullParserException e) {

			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/* Método que recorre el xml en busca de los datos */
	private void parseXML(XmlPullParser parser) throws XmlPullParserException,IOException
	{
        int eventType = parser.getEventType();
        String nombre="ERROR";
        while (eventType != XmlPullParser.END_DOCUMENT){
            String name = null;
            switch (eventType){
                case XmlPullParser.START_DOCUMENT:
        
                    break;
                case XmlPullParser.START_TAG:
                    name = parser.getName();
                    if(name.equalsIgnoreCase("nombre"))
                		nombre = parser.nextText();
                		
                    break;
                case XmlPullParser.END_TAG:
                    name = parser.getName();
                    if (name.equalsIgnoreCase("frienddata")){
                    	friendList.add(createFriend(nombre));
                    } 
            }
            eventType = parser.next();
        }

	}
	/* Método que agrega un dato a la lista */
	private HashMap<String,String> createFriend(String fn){
		HashMap<String,String> friend = new HashMap<String,String>();
		friend.put("nombre", fn);
		return friend;
	}

}
