//	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.pojo.Track;
import com.j0h1.contour.pojo.TrackResponseList;
import com.j0h1.contour.utils.RESTConfig;
import com.j0h1.contour.volley.SimpleXmlRequest;

import android.annotation.SuppressLint;
import android.app.Fragment;
import android.content.Intent;
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.ListView;
import android.widget.Toast;

/**
 * Fragment that shows the user all available tracks and lets the
 * user start a new track drawing session by selecting one of them.
 * @author Johannes Riedmann
 *
 */
public class TrackModeFragment extends Fragment {
	
	private ListView lvCategories;
	
	private String language;
	
	protected String encodedImage;
	protected byte[] imageBytes;
	
	private Toast toast;

	@Override
	public void onStart() {
		super.onStart();
		
		// get current locale for activity and set language (de/en)
		language = getResources().getConfiguration().locale.getLanguage();

		lvCategories = (ListView) getView().findViewById(R.id.lvCategories);
		
		// request a list of all non-deleted tracks persisted server-sided
		RequestQueue requestQueue = Volley.newRequestQueue(getActivity());
		
		SimpleXmlRequest<TrackResponseList> request = new SimpleXmlRequest<TrackResponseList>(
				Request.Method.GET,
				RESTConfig.BASE_URL + "tracks/language/" + language,
				TrackResponseList.class,
				new Response.Listener<TrackResponseList>() {
					@Override
					public void onResponse(TrackResponseList response) {
						if (response.getList() != null) {
							populateTrackList(response.getList());
						} else {							
							prepareToast(getString(R.string.no_tracks_found));
							toast.show();
						}
					}
				}, new Response.ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError error) {
						prepareToast(getString(R.string.connection_lost));
						toast.show();
					}
				});
		
		requestQueue.add(request);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		return inflater.inflate(R.layout.fragment_track_mode, container, false);
	}

	/**
	 * Populates the ListView with the received tracks.
	 * @param tracks Tracks received as a response from the previous request.
	 */
	private void populateTrackList(final ArrayList<Track> tracks) {
		// extract track names from Track objects and store them in an ArrayList
		ArrayList<String> tracknames = new ArrayList<String>();
		
		for (Track t : tracks) {
			tracknames.add(t.getTrackname());
		}
		
		// define ListAdapter for ListView
		ArrayAdapter<String> listAdapter = new ArrayAdapter<String>(
				getActivity(), R.layout.simplerow, tracknames);

		// populate the ListView with the ListAdapter
		lvCategories.setAdapter(listAdapter);
		lvCategories.setClickable(true);

		// when a track is clicked, start a new track session
		lvCategories.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {				
				// find current Track to extract id
				Track currentTrack = tracks.get((int) id);
				final int trackId = currentTrack.getTrackId();
				
				// start TrackSessionLoadingActivity that handles the request
				// and starts the drawing session
				Intent intent = new Intent(TrackModeFragment.this.getActivity(), 
						TrackSessionLoadingActivity.class);
				intent.putExtra("trackId", "" + trackId);
				intent.putExtra("language", language);
				startActivity(intent);
			}
		});
	}
	
	@SuppressLint("ShowToast") 
	private void prepareToast(String message) {
		if (toast != null) {
    		toast.cancel();
    	}
    	toast = Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT);
	}

}
