package fishrungames.bashgid;



import android.os.Bundle;

import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ProgressBar;

import fishrungames.bashgid.core.AlbumManager;
import fishrungames.bashgid.core.AlbumManager.AlbumFullData;
import fishrungames.bashgid.core.DatabaseGetAlbumTask;

public class PhotoFragment extends Fragment
{
	
	AlbumFullData album;
	String albumName;
	int currentPhoto;
	
	PhotoFragmentAdapter listAdapter;
	ViewPager pager;
	
	ProgressBar progressBar;
	
	public PhotoFragment()
	{
		album = null;
		albumName = "";
		currentPhoto = -1;
	}
	
	public PhotoFragment(AlbumFullData album, int currentPhoto)
	{
		this.album = album;
		this.albumName = album.name;
		this.currentPhoto = currentPhoto;
	}
	
	public PhotoFragment(String albumName, int currentPhoto)
	{
		this.album = null;
		this.albumName = albumName;
		this.currentPhoto = currentPhoto;
		RestoreAlbum();
	}
	
	@Override
    public void onSaveInstanceState(final Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("albumName", albumName);
        outState.putInt("currentPhoto", currentPhoto);
        
    }
	
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		
		if (savedInstanceState != null) {
			albumName = savedInstanceState.getString("albumName");
			currentPhoto = savedInstanceState.getInt("currentPhoto");
			RestoreAlbum();
        }
		
		View rootView = inflater.inflate(R.layout.fragment_photo_page, container, false);
		
		progressBar = (ProgressBar)rootView.findViewById(R.id.progressBar);
		
		if (album == null)
		{
		progressBar.setVisibility(View.VISIBLE);
		}
		else
		{
			progressBar.setVisibility(View.GONE);
		}

		listAdapter = new PhotoFragmentAdapter(getActivity(), album);
		
		pager = (ViewPager) rootView.findViewById(R.id.pager);
		
		pager.setAdapter(listAdapter);
		
		pager.setCurrentItem(currentPhoto);
		
		return rootView;
	}
	
	void RestoreAlbum()
	{
		album = AlbumManager.CreateEmptyAlbum();
		
		DatabaseGetAlbumTask task = new DatabaseGetAlbumTask();

		task.mHandler = MainActivity.getInstance().mHandler;

		task.execute(albumName);
	}
	
	public void SetAlbum(AlbumFullData album)
	{
		progressBar.setVisibility(View.GONE);

		this.album = album;
		
		listAdapter.album = album;
		
		listAdapter.notifyDataSetChanged();
		
		pager.setCurrentItem(currentPhoto);
	}
	
	
	
		
}