package net.somethingdreadful.MAL;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Locale;

import net.somethingdreadful.MAL.api.MALApi;
import net.somethingdreadful.MAL.api.response.User;
import net.somethingdreadful.MAL.tasks.FriendsNetworkTask;
import net.somethingdreadful.MAL.tasks.FriendsNetworkTaskFinishedListener;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.TextView;

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.squareup.picasso.Picasso;

import de.keyboardsurfer.android.widget.crouton.Crouton;
import de.keyboardsurfer.android.widget.crouton.Style;

public class FriendsActivity extends SherlockFragmentActivity implements FriendsNetworkTaskFinishedListener {
	
    Context context;
    ArrayList<User> listarray = new ArrayList<User>();
    ListViewAdapter<User> listadapter;
    GridView Gridview;
    boolean forcesync = false;
    PrefManager prefs;
    MALManager mManager;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        context = this.getApplicationContext();   
        
        setContentView(R.layout.activity_friends);
        ActionBar bar = getSupportActionBar();
        bar.setDisplayHomeAsUpEnabled(true); //go to home to actionbar
        setTitle(R.string.title_activity_friends); //set title
        
        Gridview = (GridView)findViewById(R.id.listview);
        int recource = R.layout.list_friends_with_text_item;
        
        listadapter = new ListViewAdapter<User>(context, recource);
        mManager = new MALManager(context);
        prefs = new PrefManager(context);
        
        new FriendsNetworkTask(context, forcesync, this).execute(prefs.getUser());
        refresh(false);
        
        Gridview.setOnItemClickListener(new OnItemClickListener(){ //start the profile with your friend
		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
    		Intent profile = new Intent(context, net.somethingdreadful.MAL.ProfileActivity.class);
    		profile.putExtra("username", listarray.get(position).getName());
			startActivity(profile);
		}
        });

        NfcHelper.disableBeam(this);
    }
    
    public void refresh(Boolean crouton){
    	if (crouton == true){
			Crouton.makeText(this, R.string.crouton_info_SyncDone, Style.CONFIRM).show();
    	}
        Gridview.setAdapter(listadapter);	
        listadapter.clear();
        try{
        	listadapter.supportAddAll(listarray);
        }catch (Exception e){
        	if (MALApi.isNetworkAvailable(context)){
    			Crouton.makeText(this, R.string.crouton_error_noFriends, Style.ALERT).show();
    		}else{
    			Crouton.makeText(this, R.string.crouton_error_noConnectivity, Style.ALERT).show();
    		}
        }
        listadapter.notifyDataSetChanged();
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getSupportMenuInflater().inflate(R.menu.activity_friends_view, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        final int itemId = item.getItemId();
		switch (itemId) {
		case android.R.id.home:
			finish();
			break;
		case R.id.forceSync:
			if (MALApi.isNetworkAvailable(context)){
				Crouton.makeText(this, R.string.crouton_info_SyncMessage, Style.INFO).show();
				forcesync = true;
				new FriendsNetworkTask(context, forcesync, this).execute(prefs.getUser());
			}else{
				Crouton.makeText(this, R.string.crouton_error_noConnectivity, Style.ALERT).show();
			}
			break;
		}
        return super.onOptionsItemSelected(item);
    }
	
    public class ListViewAdapter<T> extends ArrayAdapter<T> {


		public ListViewAdapter(Context context, int resource) {
            super(context, resource);
        }
		
		private String formatDate(String date) {
		    SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssZ", Locale.US); 
		    try {
                Date dateobj = dt.parse(date);
                SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd, h:m a", Locale.US);
                return dt1.format(dateobj);
            } catch (ParseException e) {
                Log.e("MALX", "error parsing date: " + e.getMessage());
                // return date without changing
                return date;
            }
		}
	    
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            final User record;
            record = ((User) listarray.get(position));
            
            try{
            	if (view == null) {
            		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            		view = inflater.inflate(R.layout.list_friends_with_text_item, parent, false);
                
            		String username =  record.getName();
            		TextView Username = (TextView) view.findViewById(R.id.userName);
            		Username.setText(username);
            		if (User.isDeveloperRecord(username)) {
            			Username.setTextColor(Color.parseColor("#8CD4D3")); //Developer
            		}
            		String last_online = record.getProfile().getDetails().getLastOnline();
            		//Set online or offline status
            		View Status = (View) view.findViewById(R.id.status);
            		if (last_online.equals("Now")){
            			Status.setBackgroundColor(Color.parseColor("#0D8500"));
            		}else{
            			Status.setBackgroundColor(Color.parseColor("#D10000"));
            		}
            		TextView since = (TextView) view.findViewById(R.id.since);
            		since.setText(record.getFriendSince() != null ? formatDate(record.getFriendSince()) : getString(R.string.unknown));
            		TextView lastonline = (TextView) view.findViewById(R.id.lastonline);
            		lastonline.setText(last_online);
            		Picasso picasso =  Picasso.with(context);
	            	picasso.load(record.getProfile().getAvatarUrl())
	            		.error(R.drawable.cover_error)
	            		.placeholder(R.drawable.cover_loading)
	            		.fit()
	            		.into((ImageView) view.findViewById(R.id.profileImg));
            	}
            }catch (Exception e){
            	e.printStackTrace();
            }
            return view;
        }

        public void supportAddAll(Collection<? extends T> collection) {
			for (T record : collection) {
	            this.add(record);
	        }
		}
	}

    @Override
    public void onFriendsNetworkTaskFinished(ArrayList<User> result) {
        if ( result != null ) {
            listarray = result;
            refresh(forcesync); // show crouton only if sync was forced
        } else {
            Crouton.makeText(this, R.string.crouton_error_Friends, Style.ALERT).show();
        }
    }
}

@@ -5730,13 +5730,13 @@
 r(%22#
-8CD4D
+00858
 3%22))

Replace friendlist developer color with a darker one.