package it.unipr.dsg.mobdev;

//Support Package import to hadle platform version prior to HoneyComb !
import android.support.v4.app.Fragment;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AddBookmarkFragment extends Fragment {

	private TextView resultTextView = null;
	private EditText nameField = null;
	private EditText urlField = null;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		Log.d(MainActivity.TAG, "AddBookmarkFragment --> onCreate()");
		super.onCreate(savedInstanceState);
	}

	@Override
	public void onDestroy() {
		Log.d(MainActivity.TAG, "AddBookmarkFragment --> onDestroy()");
		super.onDestroy();
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
		
		Log.d(MainActivity.TAG, "AddBookmarkFragment --> onCreateView()");
		
		View view = inflater.inflate(R.layout.add_bookmark,container, false);
		
		resultTextView = (TextView)view.findViewById(R.id.bookmarkResultTextView);
		nameField = (EditText)view.findViewById(R.id.bookmarkField);
		urlField = (EditText)view.findViewById(R.id.urlField);

		Button addButton = (Button)view.findViewById(R.id.addButton);
		
		addButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d(MainActivity.TAG, "AddBookmarkFragment --> AddButton:onClick()");

				String bookmarkName = nameField.getText().toString();
				String url = urlField.getText().toString();

				if(bookmarkName != null && bookmarkName.length() > 0 && url != null && url.length() > 0)
				{
					if(BookmarkManager.getInstance().addBookmark(new BookmarkDescriptor(bookmarkName.trim(), url.trim())) == 0)
					{
						Log.d(MainActivity.TAG, "AddBookmarkFragment --> Bookmark:["+bookmarkName+"@"+url+"]");
						resultTextView.setText("["+bookmarkName+"@"+url+"] Saved !");
						resultTextView.setTextColor(Color.GRAY);
						
						nameField.setText("");
						urlField.setText("");
					}
					else
					{
						Log.e(MainActivity.TAG, "AddBookmarkFragment --> Error ! Bookmark already in the list ! ");
						resultTextView.setText("Error ! Bookmark already in the list ! ");
						resultTextView.setTextColor(Color.RED);
					}
				}
				else
				{
					Log.e(MainActivity.TAG, "AddBookmarkFragment --> Error ! Invalid Bookmark Name or Url ");
					resultTextView.setText("Error ! Invalid Bookmark Name or Url ");
					resultTextView.setTextColor(Color.RED);
				}
			}
		});

		
		return view;
	}

	@Override
	public void onDestroyView() {
		Log.d(MainActivity.TAG, "AddBookmarkFragment --> onDestroyView()");
		super.onDestroyView();
	}
}