//	Contour - Android drawing teacher application
//	Copyright (C) 2014  Johannes Riedmann
//	
//	This program is free software: you can redistribute it and/or modify
//	it under the terms of the GNU General Public License as published by
//	the Free Software Foundation, either version 3 of the License, or
//	(at your option) any later version.
//	
//	This program is distributed in the hope that it will be useful,
//	but WITHOUT ANY WARRANTY; without even the implied warranty of
//	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//	GNU General Public License for more details.
//	
//	You should have received a copy of the GNU General Public License
//	along with this program.  If not, see <http://www.gnu.org/licenses/>.

package com.j0h1.contour;

import java.util.ArrayList;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;
import com.j0h1.contour.R;
import com.j0h1.contour.database.ContourDatabase;
import com.j0h1.contour.pojo.Player;
import com.j0h1.contour.pojo.Session;
import com.j0h1.contour.pojo.SessionResponseList;
import com.j0h1.contour.utils.RESTConfig;
import com.j0h1.contour.volley.SimpleXmlRequest;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.os.Bundle;
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.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Fragment that is responsible for displaying the top 10 custom sessions.
 * @author Johannes Riedmann
 *
 */
public class HighscoreCustomFragment extends Fragment {
	
	private ArrayList<Session> customSessions;	
	private ListView lvHighscoresCustom;	
	private Toast toast;
	
	@Override
	public void onStart() {
		super.onStart();
		
		lvHighscoresCustom = (ListView) getView().findViewById(R.id.lvHighscoreCustom);
		
		requestCustomSessionData();
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_highscore_custom, container, false);
	}
	
	/**
	 * Request custom session data for the local player. If there are custom sessions
	 * persisted server-sided, then populate the ListView with the meta data of
	 * the sessions.
	 */
	private void requestCustomSessionData() {
		final Player player = getLocalPlayer();
		
		// request session data for custom sessions of local player
		RequestQueue rq = Volley.newRequestQueue(getActivity());
		
		SimpleXmlRequest<SessionResponseList> request = new SimpleXmlRequest<SessionResponseList>(
				Request.Method.GET,
				RESTConfig.BASE_URL + "session/player/" + player.getPlayerId() +"/track/" + Integer.MAX_VALUE,
				SessionResponseList.class,
				new Response.Listener<SessionResponseList>() {
					@Override
					public void onResponse(SessionResponseList response) {
						if (response.getList() != null) {
							// when there is a valid response, populate the ListView
							customSessions = response.getList();
							populateListView(player);
						} else {
							// when the reponse list is null, no custom sessions
							// are persisted - give feedback
							TextView statusLabel = (TextView) getView()
									.findViewById(R.id.txtHighscoreCustomStatus);
							statusLabel.setVisibility(View.VISIBLE);
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						// if Volley responds with an error the connection to
						// the server was lost
						prepareToast(getString(R.string.connection_lost));
						toast.show();
					}
				});
		
		rq.add(request);
	}
	
	/**
	 * Fills the ListView with custom session data of the local player 
	 * received from the REST request.
	 * @param player	Locally persisted player.
	 */
	private void populateListView(Player player) {		
		ArrayList<String> sessionStrings = new ArrayList<String>();
		
		// the request responds with a descending sorted list of the (max.) 10
		// best custom sessions for the player - so we don't have to care about the
		// correct ranking of the entries (we just use i, since they are already in
		// the correct order)
		for (int i = 1; i <= customSessions.size(); i++) {
			Session currentSession = customSessions.get(i - 1);
			
			sessionStrings.add("#" + i + " " 
					+ player.getPlayername() + " "
					+ currentSession.getScore());
		}
		
		// define an ArrayAdapter for the previously defined Strings and assign it to the
		// ListView
		ListAdapter adapter = new ArrayAdapter<String>(getActivity().getApplicationContext(), 
				R.layout.simplerow, sessionStrings);
		
		lvHighscoresCustom.setAdapter(adapter);
		
		// when the user clicks on a ListView item, a SessionDetailsDialog opens with
		// more information about the selected session
		lvHighscoresCustom.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> adapter, View v, int position,
					long id) {
				SessionDetailsDialog dialog = new SessionDetailsDialog(
						getActivity(), customSessions.get(position));
				dialog.show();
			}			
		});
	}
	
	/**
	 * Gets the locally persisted player from the database.
	 * @return	Locally persisted player.
	 */
	private Player getLocalPlayer() {
		ContourDatabase db = new ContourDatabase(getActivity());
		Player player = db.findPlayer();
		db.close();
		
		return player;
	}
	
	@SuppressLint("ShowToast") 
	private void prepareToast(String message) {
		if (toast != null) {
    		toast.cancel();
    	}
    	toast = Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT);
	}

}
