package de.tudarmstadt.informatik.hostage.ui2.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import com.fortysevendeg.android.swipelistview.BaseSwipeListViewListener;

import java.util.List;

import de.tudarmstadt.informatik.hostage.R;
import de.tudarmstadt.informatik.hostage.dao.ProfileManager;
import de.tudarmstadt.informatik.hostage.model.Profile;
import de.tudarmstadt.informatik.hostage.ui2.activity.ProfileEditActivity;
import de.tudarmstadt.informatik.hostage.ui2.adapter.ProfileManagerListAdapter;
import de.tudarmstadt.informatik.hostage.ui2.swipelist.SwipeListView;

/**
 * @author Alexander Brakowski
 * @created 14.01.14 15:05
 */
public class ProfileManagerFragment extends Fragment {
	private ProfileManagerListAdapter mAdapter;

	public ProfileManagerFragment(){}

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

	    super.onCreateView(inflater, container, savedInstanceState);
	    getActivity().setTitle(getResources().getString(R.string.drawer_profile_manager));
	    setHasOptionsMenu(true);

        View rootView = inflater.inflate(R.layout.fragment_profile_manager, container, false);
	    SwipeListView list = (SwipeListView) rootView.findViewById(R.id.profile_manager_listview);

		final ProfileManager pmanager = ProfileManager.getInstance();
		pmanager.loadData();

        List<Profile> strList = pmanager.getProfilesList();

		mAdapter = new ProfileManagerListAdapter(getActivity(), strList);
		pmanager.setProfileListAdapter(mAdapter);

        list.setAdapter(mAdapter);

		list.setSwipeListViewListener(new BaseSwipeListViewListener() {
			@Override
			public void onClickFrontView(int position) {
				Profile profile = mAdapter.getItem(position);
				pmanager.activateProfile(profile);

				mAdapter.notifyDataSetChanged();
			}
		});

        return rootView;
    }

	@Override
	public void onResume() {
		super.onResume();
		mAdapter.notifyDataSetChanged();
	}

	@Override
	public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
		// Inflate the menu items for use in the action bar
		inflater.inflate(R.menu.profile_manager_actions, menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
			case R.id.profile_manager_action_add:
				Intent intent = new Intent(getActivity(), ProfileEditActivity.class);
				intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				getActivity().startActivity(intent);
				return true;
		}

		return false;
	}
}