/* Copyright (c) 2008 -- CommonsWare, LLC

	 Licensed under the Apache License, Version 2.0 (the "License");
	 you may not use this file except in compliance with the License.
	 You may obtain a copy of the License at

		 http://www.apache.org/licenses/LICENSE-2.0

	 Unless required by applicable law or agreed to in writing, software
	 distributed under the License is distributed on an "AS IS" BASIS,
	 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
	 See the License for the specific language governing permissions and
	 limitations under the License.
*/
	 
package com.commonsware.tourit;

import android.content.*;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.provider.BaseColumns;
import android.text.TextUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class Provider extends ContentProvider {
	private static final String DATABASE_NAME="tours.db";
	private static final int TOURS=1;
	private static final int TOUR_ID=2;
	private static final UriMatcher MATCHER;
	private static HashMap<String, String> TOURS_LIST_PROJECTION;
	
	public static final class Tours implements BaseColumns {
		public static final Uri CONTENT_URI
				 =Uri.parse("content://com.commonsware.android.tourit.Provider/tours");
		public static final String DEFAULT_SORT_ORDER="title";
		public static final String ID="_id";
		public static final String TITLE="title";
		public static final String DESCRIPTION="desc";
		public static final String CREATED_DATE="created";
		public static final String MODIFIED_DATE="modified";
		public static final String ROUTE="route";
	}

	static {
		MATCHER=new UriMatcher(UriMatcher.NO_MATCH);
		MATCHER.addURI("com.commonsware.android.tourit.Provider", "tours", TOURS);
		MATCHER.addURI("com.commonsware.android.tourit.Provider", "tours/#", TOUR_ID);

		TOURS_LIST_PROJECTION=new HashMap<String, String>();
		TOURS_LIST_PROJECTION.put(Provider.Tours.ID, "_id");
		TOURS_LIST_PROJECTION.put(Provider.Tours.TITLE, "title");
	}

	public String getDbName() {
		return(DATABASE_NAME);
	}
	
	public int getDbVersion() {
		return(1);
	}
	
	private class DatabaseHelper extends SQLiteOpenHelper {
		@Override
		public void onCreate(SQLiteDatabase db) {
			Cursor c=db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='tours'", null);
			
			try {
				if (c.count()==0) {
					db.execSQL("CREATE TABLE tours (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, desc TEXT DEFAULT '', created INTEGER, modified INTEGER, route TEXT DEFAULT '{}');");
					
					File sdcard=new File("/sdcard/tourit");
					
					if (sdcard.exists()) {
						for (File f : sdcard.listFiles()) {
							if (f.isDirectory()) {
								File tour=new File(f, "tour.js");
								
								if (tour.exists()) {
									long now=System.currentTimeMillis();
									ContentValues map=new ContentValues();
									
									map.put("title", f.getName());
									map.put("created", now);
									map.put("modified", now);
									map.put("route", tour.getPath());
									
									db.insert("tours", null, map);
								}
							}
						}
					}
				}
			}
			finally {
				c.close();
			}
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			android.util.Log.w("TourIt", "Upgrading database, which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS tours");
			onCreate(db);
		}
	}
	
	private SQLiteDatabase db;
	
	@Override
	public boolean onCreate() {
		db=(new DatabaseHelper()).openDatabase(getContext(), getDbName(), null, getDbVersion());
		
		return (db == null) ? false : true;
	}
	
	@Override
	public Cursor query(Uri url, String[] projection, String selection,
												String[] selectionArgs, String sort) {
		SQLiteQueryBuilder qb=new SQLiteQueryBuilder();

		qb.setTables(getTableName());
		
		if (isCollectionUri(url)) {
			qb.setProjectionMap(getDefaultProjection());
		}
		else {
			qb.appendWhere(getIdColumnName()+"=" + url.getPathSegments().get(1));
		}
		
		String orderBy;
		
		if (TextUtils.isEmpty(sort)) {
			orderBy=getDefaultSortOrder();
		} else {
			orderBy=sort;
		}
		
		Cursor c=qb.query(db, projection, selection, selectionArgs, null, null, orderBy);
		c.setNotificationUri(getContext().getContentResolver(), url);
		return c;
	}

	@Override
	public String getType(Uri url) {
		if (isCollectionUri(url)) {
			return(getCollectionType());
		}
		
		return(getSingleType());
	}

	@Override
	public Uri insert(Uri url, ContentValues initialValues) {
		long rowID;
		ContentValues values;
		
		if (initialValues!=null) {
			values=new ContentValues(initialValues);
		} else {
			values=new ContentValues();
		}

		if (!isCollectionUri(url)) {
			throw new IllegalArgumentException("Unknown URL " + url);
		}
		
		for (String colName : getRequiredColumns()) {
			if (values.containsKey(colName) == false) {
				throw new IllegalArgumentException("Missing column: "+colName);
			}
		}

		populateDefaultValues(values);

		rowID=db.insert(getTableName(), getNullColumnHack(), values);
		if (rowID > 0) {
			Uri uri=ContentUris.withAppendedId(getContentUri(), rowID);
			getContext().getContentResolver().notifyChange(uri, null);
			return uri;
		}

		throw new SQLException("Failed to insert row into " + url);
	}

	@Override
	public int delete(Uri url, String where, String[] whereArgs) {
		int count;
		long rowId=0;
		
		if (isCollectionUri(url)) {
			count=db.delete(getTableName(), where, whereArgs);
		}
		else {
			String segment=url.getPathSegments().get(1);
			rowId=Long.parseLong(segment);
			count=db
					.delete(getTableName(), getIdColumnName()+"="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
		}

		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}

	@Override
	public int update(Uri url, ContentValues values, String where, String[] whereArgs) {
		int count;
		
		if (isCollectionUri(url)) {
			count=db.update(getTableName(), values, where, whereArgs);
		}
		else {
			String segment=url.getPathSegments().get(1);
			count=db
					.update(getTableName(), values, getIdColumnName()+"="
							+ segment
							+ (!TextUtils.isEmpty(where) ? " AND (" + where
									+ ')' : ""), whereArgs);
		}
	
		getContext().getContentResolver().notifyChange(url, null);
		return count;
	}
	
	private boolean isCollectionUri(Uri url) {
		return(MATCHER.match(url)==TOURS);
	}
	
	private HashMap<String, String> getDefaultProjection() {
		return(TOURS_LIST_PROJECTION);
	}
	
	private String getTableName() {
		return("tours");
	}
	
	private String getIdColumnName() {
		return("_id");
	}
	
	private String getDefaultSortOrder() {
		return("title");
	}
	
	private String getCollectionType() {
		return("vnd.android.cursor.dir/vnd.commonsware.tour");
	}
	
	private String getSingleType() {
		return("vnd.android.cursor.item/vnd.commonsware.tour");
	}
	
	private String[] getRequiredColumns() {
		return(new String[] {"title"});
	}
	
	private void populateDefaultValues(ContentValues values) {
		Long now=Long.valueOf(System.currentTimeMillis());
		Resources r=Resources.getSystem();

		if (values.containsKey(Provider.Tours.CREATED_DATE) == false) {
			values.put(Provider.Tours.CREATED_DATE, now);
		}

		if (values.containsKey(Provider.Tours.MODIFIED_DATE) == false) {
			values.put(Provider.Tours.MODIFIED_DATE, now);
		}

		if (values.containsKey(Provider.Tours.DESCRIPTION) == false) {
			values.put(Provider.Tours.DESCRIPTION, "");
		}
		
		if (values.containsKey(Provider.Tours.ROUTE) == false) {
			values.put(Provider.Tours.ROUTE, "{}");
		}
	}
	
	private String getNullColumnHack() {
		return("desc");
	}
	
	private Uri getContentUri() {
		return(Provider.Tours.CONTENT_URI);
	}
}