package jp.sourceforge.nicoro;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Browser;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class Bookmarks extends ListActivity {
	
	public static final String INTENT_NAME_URL = "URL";
	public static final String INTENT_NAME_TITLE = "TITLE";
	
	private static final String KEY_URL = "url";
	private static final String KEY_TITLE = "title";
	
	private static final int POSITION_ADD_BOOKMARK = 0;
	
	private ArrayList<HashMap<String, Object>> mBookmarkList;
	
	private String mAddBookmarkUrl;
	private String mAddBookmarkTitle;
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        Intent intent = getIntent();
        if (intent != null) {
        	mAddBookmarkUrl = intent.getStringExtra(INTENT_NAME_URL);
        	mAddBookmarkTitle = intent.getStringExtra(INTENT_NAME_TITLE);
        }
        
        ListView listView = getListView();
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				ListView listView = (ListView) parent;
				ListAdapter adapter = listView.getAdapter();
				if (position == POSITION_ADD_BOOKMARK) {
					Bookmarks.addBookmark(Bookmarks.this,
							mAddBookmarkTitle, mAddBookmarkUrl);
				} else {
					HashMap<String, Object> bookmark =
						(HashMap<String, Object>) adapter.getItem(position);
					
					Intent intent = new Intent(
							Intent.ACTION_VIEW,
							Uri.parse((String) bookmark.get(KEY_URL)),
							getApplicationContext(), NicoroWebBrowser.class);
					intent.addCategory(Intent.CATEGORY_BROWSABLE);
					startActivityIfNeeded(intent, 0);
				}
			}
        });
        final int colorBG = getResources().getColor(
        		R.color.bookmark_background);
        listView.setBackgroundColor(colorBG);
        listView.setCacheColorHint(colorBG);
    }
    
    @Override
    protected void onResume() {
    	super.onResume();

        createBookmarkList();
        setListAdapter(createAdapter());
    }

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
	}
    
    private void createBookmarkList() {
    	ContentResolver cr = getContentResolver();
    	Cursor c = cr.query(Browser.BOOKMARKS_URI,
    			new String[] {
	    			Browser.BookmarkColumns.URL,
	    			Browser.BookmarkColumns.TITLE },
    			"bookmark = 1", null, null);
    	try {
    		if (mBookmarkList == null) {
    			mBookmarkList = new ArrayList<HashMap<String, Object>>(c.getCount() + 1);
    		} else {
    			mBookmarkList.clear();
    		}
    		
			// ブックマーク追加用の特別項目追加
    		if (mAddBookmarkUrl != null) {
				HashMap<String, Object> bookmark = Util.newHashMap(2);
				bookmark.put(KEY_URL, mAddBookmarkUrl);
				bookmark.put(KEY_TITLE, getString(R.string.bookmarks_add_boookmark));
				mBookmarkList.add(bookmark);
    		}
    		
    		if (c.moveToFirst()) {
    			Matcher matcher = Pattern.compile(
    					NicoroAPIManager.PATTERN_NICOVIDEO_URL).matcher("");
    			do {
        			final int indexUrl = c.getColumnIndex(
        					Browser.BookmarkColumns.URL);
    				final String url = c.getString(indexUrl);
            		matcher.reset(url);
            		if (matcher.find()) {
            			final int indexTitle = c.getColumnIndex(
            					Browser.BookmarkColumns.TITLE);
	    				final String title = c.getString(indexTitle);
	    				
	    				HashMap<String, Object> bookmark = Util.newHashMap(2);
	    				bookmark.put(KEY_URL, url);
	    				bookmark.put(KEY_TITLE, title);
	    				mBookmarkList.add(bookmark);
            		}
    			} while (c.moveToNext());
    		}
    		
    		mBookmarkList.trimToSize();
    	} finally {
    		c.close();
    	}
    }
    
    private ListAdapter createAdapter() {
        SimpleAdapter adapter = new SimpleAdapter(
        		getApplicationContext(),
        		mBookmarkList,
        		R.layout.bookmarks,
        		new String []{KEY_TITLE, KEY_URL},
        		new int []{android.R.id.text1, android.R.id.text2}
        		);
        return adapter;
    }
    
    public static void addBookmark(Activity activity, String title, String url) {
		Matcher matcher = Pattern.compile(NicoroAPIManager.PATTERN_NICOVIDEO_URL).matcher(url);
		if (matcher.find()) {
			Browser.saveBookmark(activity, title, url);
		} else {
			Util.showErrorToast(activity.getApplicationContext(),
					R.string.toast_bookmark_url_not_nicovideo);
		}
    }
}
