package jp.sourceforge.nicoro;

import static jp.sourceforge.nicoro.Log.LOG_TAG;

import java.text.DateFormat;
import java.util.ArrayList;
import java.util.Date;

import jp.sourceforge.nicoro.RelatedVideoLoader.Video;

import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class RelatedVideoActivity extends ListActivity {
    private static final boolean DEBUG_LOGD = Release.IS_DEBUG && true;
    private static final boolean DEBUG_LOGV = Release.IS_DEBUG && false;

    private static final int MSG_ID_LOAD_FINISHED = 0;
	private static final int MSG_ID_LOAD_OCCURED_ERROR = 1;

	private String mVideoNumber;
	private int mPage;
	private RelatedVideoLoader mRelatedVideoLoader;
	private ArrayList<RelatedVideoLoader.Video> mVideos;
	private RelatedVideoListAdapter mAdapter;
	private ProgressDialog mProgressDialogNowLoading;

	private String mResStringInfoCountPlay;
	private String mResStringInfoCountComment;
	private String mResStringInfoCountMylist;
	private String mResStringUpload;

	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
            if (mHandler == null) {
                if (DEBUG_LOGD) {
                    Log.d(LOG_TAG, Log.buf().append("Activity was destroyed. ignore message=")
                            .append(msg.toString()).toString());
                }
                return;
            }
			switch (msg.what) {
			case MSG_ID_LOAD_FINISHED:
				ArrayList<RelatedVideoLoader.Video> videos =
					(ArrayList<Video>) msg.obj;
				int totalCount = mRelatedVideoLoader.getTotalCount();
				if (totalCount == 0 && videos.size() == 0
						&& mVideos.size() == 0) {
					Util.showCloseDialog(RelatedVideoActivity.this,
							null,
							getString(R.string.dialog_message_related_video_zero),
							true);
				} else {
					mVideos.ensureCapacity(totalCount);
					mVideos.addAll(videos);

					if (mPage < mRelatedVideoLoader.getPageCount()) {
						++mPage;
						createAndStartRelatedVideoLoader();
					} else {
//						getListView().removeFooterView(mProgress);
						if (mProgressDialogNowLoading != null) {
							mProgressDialogNowLoading.dismiss();
							mProgressDialogNowLoading = null;
						}
						assert mPage == mRelatedVideoLoader.getPageCount();
						mAdapter.setCount(mVideos.size());
					}
				}
				break;
			case MSG_ID_LOAD_OCCURED_ERROR:
				String errorMessage = (String) msg.obj;
				Util.showErrorDialog(RelatedVideoActivity.this,
						errorMessage, true);
				break;
			default:
				assert false : msg.what;
				break;
			}
		}
	};


	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Resources res = getResources();
		mResStringInfoCountPlay = res.getString(R.string.info_count_play);
		mResStringInfoCountComment = res.getString(R.string.info_count_comment);
		mResStringInfoCountMylist = res.getString(R.string.info_count_mylist);
		mResStringUpload = res.getString(R.string.upload);

		Intent intent = getIntent();
        String videoNumber = intent.getStringExtra(AbstractNicoroPlayer.INTENT_NAME_VIDEO_NUMBER);
        mVideoNumber = videoNumber;
        mPage = 1;
        mVideos = new ArrayList<Video>();

        createAndStartRelatedVideoLoader();

        ListView listView = getListView();
//        mProgress = getLayoutInflater().inflate(
//        		R.layout.listview_progress_footer, listView, false);
//        listView.addFooterView(mProgress, null, false);
        mAdapter = new RelatedVideoListAdapter();
        listView.setAdapter(mAdapter);
        final int colorBG = res.getColor(
        		R.color.related_video_background);
        listView.setBackgroundColor(colorBG);
        listView.setCacheColorHint(colorBG);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				String url = mVideos.get(position).url;
				Intent intent = new Intent(
						Intent.ACTION_VIEW,
						Uri.parse(url),
						getApplicationContext(), NicoroWebBrowser.class);
				intent.addCategory(Intent.CATEGORY_BROWSABLE);
				startActivityIfNeeded(intent, 0);
				finish();
			}
        });

        mProgressDialogNowLoading = Util.createProgressDialogLoading(
        		this, R.string.now_loading,
        		new DialogInterface.OnCancelListener() {
					@Override
					public void onCancel(DialogInterface dialog) {
						finish();
					}
				});

        mProgressDialogNowLoading.show();
	}

	@Override
	protected void onDestroy() {
		// TODO: ANR対策の為に***Loader類のabort対応が必要
		if (mRelatedVideoLoader != null) {
			mRelatedVideoLoader.finish();
			mRelatedVideoLoader = null;
		}
		super.onDestroy();
		mHandler = null;
	}

    @Override
    protected void finalize() throws Throwable {
    	try {
            if (DEBUG_LOGV) {
                Log.v(LOG_TAG, "RelatedVideoActivity#finalize start");
            }
    		super.finalize();
    	} finally {
    		if (mRelatedVideoLoader != null) {
    			mRelatedVideoLoader.finish();
    		}
            if (DEBUG_LOGV) {
                Log.v(LOG_TAG, "RelatedVideoActivity#finalize start");
            }
    	}
    }

    private void createAndStartRelatedVideoLoader() {
        assert mHandler != null;
		RelatedVideoLoader loader = new RelatedVideoLoader(mVideoNumber, mPage);
		mRelatedVideoLoader = loader;
		loader.registerMessageOnFinished(mHandler.obtainMessage(
				MSG_ID_LOAD_FINISHED));
		loader.registerMessageOnOccurredError(mHandler.obtainMessage(
				MSG_ID_LOAD_OCCURED_ERROR));
		loader.startLoad();
    }

    private class RelatedVideoListAdapter extends BaseAdapter {
    	private int mCount = 0;
    	private DateFormat mDateFormat = DateFormat.getDateTimeInstance(
    			DateFormat.LONG, DateFormat.DEFAULT);
    	private ThumbnailCacher mThumbnailCacher =
    	    NicoroApplication.getInstance(RelatedVideoActivity.this)
    	    .getThumbnailCacher();

		@Override
		public int getCount() {
			return mCount;
		}

		@Override
		public Object getItem(int position) {
			// TODO 自動生成されたメソッド・スタブ
			return null;
		}

		@Override
		public long getItemId(int position) {
			// TODO 自動生成されたメソッド・スタブ
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View view;
			ListItem listItem;
			if (convertView == null) {
				LayoutInflater inflater = getLayoutInflater();
				view = inflater.inflate(R.layout.related_video, parent, false);
				listItem = new ListItem();
				view.setTag(listItem);
				listItem.time = (VariableLabelView) view.findViewById(R.id.time);
				listItem.title = (VariableLabelView) view.findViewById(R.id.title);
				listItem.view = (VariableLabelView) view.findViewById(R.id.view);
				listItem.comment = (VariableLabelView) view.findViewById(R.id.comment);
				listItem.mylist = (VariableLabelView) view.findViewById(R.id.mylist);
				listItem.length = (VariableLabelView) view.findViewById(R.id.length);
				listItem.thumbnail = (ImageView) view.findViewById(R.id.thumbnail);
			} else {
				view = convertView;
				listItem = (ListItem) convertView.getTag();
			}
			Video video = mVideos.get(position);

			listItem.time.getTextBuilderWithClear().append(mDateFormat.format(
					new Date(video.time * 1000L)))
					.append(" ").append(mResStringUpload);
			listItem.time.notifyUpdateText();

			listItem.title.setText(video.title);

			listItem.view.getTextBuilderWithClear().append(mResStringInfoCountPlay).append(video.view);
			listItem.view.notifyUpdateText();

			listItem.comment.getTextBuilderWithClear().append(mResStringInfoCountComment).append(video.comment);
			listItem.comment.notifyUpdateText();

			listItem.mylist.getTextBuilderWithClear().append(mResStringInfoCountMylist).append(video.mylist);
			listItem.mylist.notifyUpdateText();

			Util.appendPlayTime(listItem.length.getTextBuilderWithClear(),
					video.length / 60, video.length % 60);
			listItem.length.notifyUpdateText();

			ViewGroup.LayoutParams params = listItem.thumbnail.getLayoutParams();
			Bitmap bitmap = mThumbnailCacher.getThumbnail(video.thumbnail);
			AsyncBitmapDrawable drawable;
			if (bitmap == null) {
				drawable = new AsyncBitmapDrawable(params.width, params.height);
				mThumbnailCacher.loadThumbnail(video.thumbnail,
				        new CallbackMessage<Bitmap, Void>(
				                drawable.getHandler(), 0));
			} else {
				drawable = new AsyncBitmapDrawable(bitmap,
						params.width, params.height);
			}
			listItem.thumbnail.setImageDrawable(drawable);

			return view;
		}

		public void setCount(int count) {
			boolean invalidate = (mCount != count);
			mCount = count;
			if (invalidate) {
				getListView().invalidateViews();
			}
		}
    }

    private static class ListItem {
    	public int position;

    	public VariableLabelView time;
    	public VariableLabelView title;
    	public VariableLabelView view;
    	public VariableLabelView comment;
    	public VariableLabelView mylist;
    	public VariableLabelView length;
    	public ImageView thumbnail;
    }
}
