package com.example.db01;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Environment;
import android.util.Log;

public class DbAdapter 
{
	 
	 	public  String TABLE_ALARM = "alarm";
		public  String COL_ID = "_id";
		public static final String COL_CREATEDTIME = "created_time";
		public static final String COL_MODIFIEDTIME = "modified_time";
		public static final String COL_NAME = "name";
		public static final String COL_FROMDATE = "from_date";
		public static final String COL_TODATE = "to_date";
		public static final String COL_RULE = "rule";
		public static final String COL_INTERVAL = "interval";
		public static final String COL_SOUND = "sound";
/**/		
		public static final String TABLE_ALARMTIME = "alarmtime";
		public static final String COL_ALARMID = "alarm_id";
		protected String COL_AT = "at";
/**/
		private static final String TAG = "ContactsDbAdapter";
		private DatabaseHelper mDbHelper;
		private SQLiteDatabase mDb;

		private static final String DATABASE_NAME = "Agenda02.db";
		private static final String SQLITE_TABLE = "alarm";
		private static final int DATABASE_VERSION = 1;

		private final Context mCtx;

		public static final String DEFAULT_DATE_FORMAT = "yyyy-M-d";

	
		String DATABASE_CREATE_ALARM = Sql_table_alarm();
		String DATABASE_CREATE_ALARMTIME = Sql_table_alarmTime();
		
		public static final SimpleDateFormat sdf = new SimpleDateFormat(DEFAULT_DATE_FORMAT);
		
		String Sql_table_alarm()
		{
			return Utils.concat("CREATE TABLE ", TABLE_ALARM, " (",
					COL_ID, " INTEGER PRIMARY KEY AUTOINCREMENT, ",
					COL_CREATEDTIME, " INTEGER, ",
					COL_MODIFIEDTIME, " INTEGER, ",
					COL_NAME, " TEXT, ",
					COL_FROMDATE, " DATE, ",
					COL_TODATE, " DATE, ",
					COL_RULE, " TEXT, ",				
					COL_INTERVAL, " TEXT, ",
					COL_SOUND, " INTEGER",
					");");
		}
		
		String Sql_table_alarmTime() 
		{
			return Utils.concat("CREATE TABLE ", TABLE_ALARMTIME, " (",
					COL_ID, " INTEGER PRIMARY KEY AUTOINCREMENT, ",
					COL_ALARMID, " INTEGER, ",
					COL_AT, " INTEGER",
					");");
		}
		
		
		

		 private class DatabaseHelper extends SQLiteOpenHelper // private static class
		 {
		
				  DatabaseHelper(Context context)
				  {
					  super(context, DATABASE_NAME, null, DATABASE_VERSION);
				  }
		
		
				  @Override
				  public void onCreate(SQLiteDatabase db)
				  {
					  Log.w(TAG, DATABASE_CREATE_ALARM);
					  db.execSQL(DATABASE_CREATE_ALARM);
					  
					  Log.w(TAG, DATABASE_CREATE_ALARMTIME);
					  db.execSQL(DATABASE_CREATE_ALARMTIME);
				  }
		
				  @Override
				  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
				  {
					   //Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
					   //  + newVersion + ", which will destroy all old data");
					   //db.execSQL("DROP TABLE IF EXISTS " + SQLITE_TABLE);
					   
					   db.execSQL("DROP TABLE IF EXISTS " + TABLE_ALARM);
					   db.execSQL("DROP TABLE IF EXISTS " + TABLE_ALARMTIME);
					  // db.execSQL("DROP TABLE IF EXISTS " + TABLE_ALARMMSG);
					   
					   
					   onCreate(db);
				  }
		 }

		 public DbAdapter(Context ctx)
		 {
			this.mCtx = ctx;
		 }

		 public DbAdapter open() throws SQLException 
		 {
			 mDbHelper = new DatabaseHelper(mCtx);
			 mDb = mDbHelper.getWritableDatabase();
			 return this;
		 }

		 public void close()
		 {
			 if(mDbHelper != null)
			 {
				 mDbHelper.close();
			 }
		 }
	
		 public long addAlarm(Alarm obj)
		 {
		 					ContentValues vals = new ContentValues();
		 					long now = System.currentTimeMillis();
		 					vals.put(COL_CREATEDTIME, now);
		 					vals.put(COL_MODIFIEDTIME, now);
		 					vals.put(COL_NAME, obj.getName());
		 					vals.put(COL_FROMDATE, obj.getFromDate());
		 					vals.put(COL_TODATE, obj.getToDate());
		 					vals.put(COL_RULE, obj.getRule());
		 					vals.put(COL_INTERVAL, obj.getInterval());
		 					vals.put(COL_SOUND, obj.getSound());
		 					long id = mDb.insert(TABLE_ALARM, null, vals);
		 					return id;
		 					//mDb.close();
		 }
		 
		 public long addAlarmTime(AlarmTime obj)
		 {
		 					ContentValues vals = new ContentValues();
		 					vals.put(COL_ALARMID, obj.getAlarmId());
		 					vals.put(COL_AT, obj.getAt());
		 					long id = mDb.insert(TABLE_ALARMTIME, null, vals);
		 					return id;
		 					//mDb.close();
		 }
		 
		 public void populate(long alarmId, SQLiteDatabase db)
		 {

				 String populateSQL = Utils.concat("SELECT ",
							"a."+Alarm.COL_FROMDATE+", ",
							"a."+Alarm.COL_TODATE+", ",
							"a."+Alarm.COL_RULE+", ",
							"a."+Alarm.COL_INTERVAL+", ",
							"at."+AlarmTime.COL_AT,
							" FROM "+Alarm.TABLE_NAME+" AS a",
							" JOIN "+AlarmTime.TABLE_NAME+" AS at",
							" ON a."+Alarm.COL_ID+" = at."+AlarmTime.COL_ALARMID,
							" WHERE a."+Alarm.COL_ID+" = ?"); 
			 
			 
			 			String[] selectionArgs = {String.valueOf(alarmId)};
			 			Cursor c = db.rawQuery(populateSQL, selectionArgs);
				
			 			if (c.moveToFirst()) 
			 			{			
							Calendar cal = Calendar.getInstance(); 			
							AlarmMsg alarmMsg = new AlarmMsg();
							long now = System.currentTimeMillis();
							db.beginTransaction();
			        try {
						do {
							Date fromDate = sdf.parse(c.getString(0)); //yyyy-M-d
							cal.setTime(fromDate);
							
							//at
							String[] tokens = c.getString(4).split(":"); //hh:mm
							cal.set(Calendar.HOUR_OF_DAY, Integer.parseInt(tokens[0]));
							cal.set(Calendar.MINUTE, Integer.parseInt(tokens[1]));
							cal.set(Calendar.SECOND, 0);
							cal.set(Calendar.MILLISECOND, 0);
							
							String rule = c.getString(2); //every day month
							String interval = c.getString(3); //mm hh dd MM yy
							
							if (rule == null && interval == null) {//one time
								alarmMsg.reset();
								alarmMsg.setAlarmId(alarmId);
								alarmMsg.setDateTime(cal.getTimeInMillis());
								if (alarmMsg.getDateTime() < now-Util.MIN)
									alarmMsg.setStatus(AlarmMsg.EXPIRED);
								alarmMsg.save(db);						
								
							} 
							
							else
							{	//repeating
										if (rule != null) 
										{						
											tokens = rule.split(" ");
											interval = "0 0 1 0 0"; //date++;
/*											
											//Day
											if (!"0".equals(tokens[1])) 
											{
												cal.set(Calendar.DAY_OF_WEEK, Integer.parseInt(tokens[1]));
												interval = "0 0 7 0 0"; //week++;
											}
											//Every
											if (!"0".equals(tokens[0]) && "0".equals(tokens[1]))
											{
												cal.set(Calendar.DATE, Integer.parseInt(tokens[0]));
												interval = "0 0 0 1 0"; //month++;
											}
											//Month
											if (!"0".equals(tokens[2]))
											{
												cal.set(Calendar.MONTH, Integer.parseInt(tokens[2])-1);
												interval = "0 0 0 0 1"; //year++;
											}
		
											while(cal.getTime().before(fromDate)) {
												nextDate(cal, interval);
											}
*/											
										}
/*										
										Date toDate = sdf.parse(c.getString(1));
										toDate.setHours(0);
										toDate.setMinutes(0);
										toDate.setSeconds(0);
										toDate.setDate(toDate.getDate()+1);
										while(cal.getTime().before(toDate)) 
										{
												alarmMsg.reset();
												alarmMsg.setAlarmId(alarmId);
												alarmMsg.setDateTime(cal.getTimeInMillis());
												if (alarmMsg.getDateTime() < now-Util.MIN)
													alarmMsg.setStatus(AlarmMsg.EXPIRED);
												alarmMsg.save(db);
												nextDate(cal, interval);
										}	
*/					
							}					
							
						} while(c.moveToNext());
						
				        db.setTransactionSuccessful();
				    } catch (Exception e) {
//				    	Log.e(TAG, e.getMessage(), e);
				    } finally {
				    	db.endTransaction();
				    }
				}
				c.close();
			}

}