/*
 * The MIT License
 *
 * Copyright 2014 Masahiko, SAWAI <masahiko.sawai@gmail.com>.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
package com.example.hello.android.ui_pattern_listview_detail_editor;

import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.TextView;
import com.example.hello.android.ui_pattern_listview_detail_editor.db.UserDBConstants;
import com.example.hello.android.ui_pattern_listview_detail_editor.db.UserDBHelper;

public class UserDetailActivity extends ListActivity
	implements UserDBConstants, OnItemClickListener
{

	public static final String EXTRA_USER_ID = UserDetailActivity.class.getPackage() + ".EXTRA_USER_ID";
	private static final int REQUEST_CODE_EDIT_NAME = 0;
	private static final int REQUEST_CODE_EDIT_EMAIL = 1;
	private static final int REQUEST_CODE_EDIT_AGE = 2;
	private static final int POSITION_NAME = 0;
	private static final int POSITION_EMAIL = 1;
	private static final int POSITION_AGE = 2;
	private static final String LOG_TAG = "XXX";
	private LayoutInflater inflator;
	private SQLiteDatabase db;
	private UserDetailListAdapter listAdapter;
	private long currentId;
	private User user;

	public void onItemClick(AdapterView<?> parent, View view, int position, long id)
	{
		switch (position)
		{
			case POSITION_NAME:
				Intent editNameIntent = new Intent(this, EditNameActivity.class);
				editNameIntent.putExtra(EditNameActivity.EXTRA_USER_NAME, user.getName());
				startActivityForResult(editNameIntent, REQUEST_CODE_EDIT_NAME);
				break;
			case POSITION_EMAIL:
				Intent editEMailIntent = new Intent(this, EditEmailActivity.class);
				editEMailIntent.putExtra(EditEmailActivity.EXTRA_USER_EMAIL, user.getEmail());
				startActivityForResult(editEMailIntent, REQUEST_CODE_EDIT_EMAIL);
				break;
			case POSITION_AGE:
				Intent editAgeIntent = new Intent(this, EditAgeActivity.class);
				editAgeIntent.putExtra(EditAgeActivity.EXTRA_USER_AGE, String.valueOf(user.getAge()));
				startActivityForResult(editAgeIntent, REQUEST_CODE_EDIT_AGE);
				break;
			default:
				throw new AssertionError();
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		Log.v(LOG_TAG, "onActivityResult() : Hello");
		if (resultCode == RESULT_OK)
		{
			if (requestCode == REQUEST_CODE_EDIT_NAME)
			{
				String name = data.getStringExtra(EditNameActivity.EXTRA_USER_NAME);
				user.setName(name);
				listAdapter.notifyDataSetChanged();
			}
			else if (requestCode == REQUEST_CODE_EDIT_EMAIL)
			{
				String email = data.getStringExtra(EditEmailActivity.EXTRA_USER_EMAIL);
				user.setEmail(email);
				listAdapter.notifyDataSetChanged();
			}
			else if (requestCode == REQUEST_CODE_EDIT_AGE)
			{
				String ageString = data.getStringExtra(EditAgeActivity.EXTRA_USER_AGE);
				int age = Integer.parseInt(ageString);
				user.setAge(age);
				listAdapter.notifyDataSetChanged();
			}
		}
		Log.v(LOG_TAG, "onActivityResult() : Bye");
	}

	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.user_detail_list_activity);

		inflator = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

		// Init data
		UserDBHelper userDBHelper = new UserDBHelper(this);
		db = userDBHelper.getReadableDatabase();

		// Init ListAdapter
		listAdapter = new UserDetailListAdapter();
		setListAdapter(listAdapter);

		// Init ListView
		getListView().setOnItemClickListener(this);

		Intent intent = getIntent();
		currentId = intent.getLongExtra(EXTRA_USER_ID, -1);
		if (currentId == -1)
		{
			createNewUser();
		}
		else
		{
			loadUserData();
		}
	}

	@Override
	protected void onPause()
	{
		Log.v(LOG_TAG, "onPause() : Hello");
		saveUserData();
		super.onPause();
		Log.v(LOG_TAG, "onPause() : Bye");
	}

	private void loadUserData()
	{
		Log.v(LOG_TAG, "loadUserData() : Hello");
		if (currentId != -1)
		{
			String selection = Columns.ID + " = ?";
			String[] selectionArgs =
			{
				String.valueOf(currentId)
			};
			Cursor cursor = db.query(TABLE_NAME, null, selection, selectionArgs, null, null, null);

			if (cursor != null)
			{
				try
				{
					if (cursor.moveToFirst())
					{
						int nameIndex = cursor.getColumnIndex(Columns.NAME);
						int emailIndex = cursor.getColumnIndex(Columns.EMAIL);
						int ageIndex = cursor.getColumnIndex(Columns.AGE);

						String name = cursor.getString(nameIndex);
						String email = cursor.getString(emailIndex);
						int age = cursor.getInt(ageIndex);
						user = new User(name, email, age);
						Log.d(LOG_TAG, "loadUserData() : loaded user => " + user);
					}
				}
				finally
				{
					cursor.close();
				}
			}
		}
		else
		{
			user = new User("No name", "", 0);
			Log.d(LOG_TAG, "loadUserData() : new  user => " + user);
			saveUserData();
		}

		Log.v(LOG_TAG, "loadUserData() : Bye");
	}

	private void saveUserData()
	{
		Log.v(LOG_TAG, "saveUserData() : Hello");

		ContentValues values = new ContentValues();
		values.put(Columns.NAME, user.getName());
		values.put(Columns.EMAIL, user.getEmail());
		values.put(Columns.AGE, user.getAge());

		String selection = Columns.ID + " = ?";
		String[] selectionArgs =
		{
			String.valueOf(currentId)
		};
		db.update(TABLE_NAME, values, selection, selectionArgs);
		Log.d(LOG_TAG, "saveUserData() : saved user => " + user);

		Log.v(LOG_TAG, "saveUserData() : Bye");
	}

	private void createNewUser()
	{
		Log.v(LOG_TAG, "createNewUser() : Hello");

		user = new User("No name", "", 0);
		Log.d(LOG_TAG, "createNewUser() : created user => " + user);

		ContentValues values = new ContentValues();
		values.put(Columns.NAME, user.getName());
		values.put(Columns.EMAIL, user.getEmail());
		values.put(Columns.AGE, user.getAge());
		currentId = db.insert(TABLE_NAME, null, values);

		Log.v(LOG_TAG, "createNewUser() : Bye");
	}

	class UserDetailListAdapter extends BaseAdapter
	{

		public int getCount()
		{
			return 3;
		}

		public Object getItem(int position)
		{
			Object result = null;
			switch (position)
			{
				case POSITION_NAME:
					result = user.getName();
					break;
				case POSITION_EMAIL:
					result = user.getEmail();
					break;
				case POSITION_AGE:
					result = user.getAge();
					break;
				default:
					Log.e(LOG_TAG, "Illegal position => " + position);
			}
			return result;
		}

		public long getItemId(int position)
		{
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent)
		{
			View itemView;
			if (convertView == null)
			{
				itemView = inflator.inflate(R.layout.user_detail_list_item, null);
			}
			else
			{
				itemView = convertView;
			}

			View nameContainer = itemView.findViewById(R.id.user_name_container);
			View emailContainer = itemView.findViewById(R.id.user_email_container);
			View ageContainer = itemView.findViewById(R.id.user_age_container);

			nameContainer.setVisibility(View.GONE);
			emailContainer.setVisibility(View.GONE);
			ageContainer.setVisibility(View.GONE);

			switch (position)
			{
				case POSITION_NAME:
					TextView nameTextView = (TextView) itemView.findViewById(R.id.user_name_textview);
					nameTextView.setText(user.getName());
					nameContainer.setVisibility(View.VISIBLE);
					break;
				case POSITION_EMAIL:
					TextView emailTextView = (TextView) itemView.findViewById(R.id.user_email_textview);
					emailTextView.setText(user.getEmail());
					emailContainer.setVisibility(View.VISIBLE);
					break;
				case POSITION_AGE:
					TextView ageTextView = (TextView) itemView.findViewById(R.id.user_age_textview);
					ageTextView.setText(String.valueOf(user.getAge()));
					ageContainer.setVisibility(View.VISIBLE);
					break;
				default:
					Log.e(LOG_TAG, "Illegal position => " + position);
			}

			return itemView;
		}
	}
}
