package nerd.tuxmobil.fahrplan.congress;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import nerd.tuxmobil.fahrplan.congress.FahrplanContract.LecturesTable;
import nerd.tuxmobil.fahrplan.congress.FahrplanContract.LecturesTable.Columns;

public class DateFieldValidation {

    final protected SQLiteOpenHelper mLecturesDatabase;

    final protected List<ValidationError> mValidationErrors;

    public DateFieldValidation(Context context) {
        mLecturesDatabase = new LecturesDBOpenHelper(context);
        mValidationErrors = new ArrayList<ValidationError>();
    }

    /**
     * Returns a list of validation errors or null.
     */
    public List<ValidationError> getValidationErrors() {
        return mValidationErrors;
    }

    /**
     * Prints all validation errors.
     */
    public void printValidationErrors() {
        for (ValidationError validationError : mValidationErrors) {
            MyApp.LogDebug(getClass().getName(), validationError.toString());
        }
    }

    /**
     * Returns true if the time stamps in the "date" fields of
     * each "event" are within a valid time range.
     * The time range is defined by the "date" attribute of
     * the "day" fields. Otherwise false is returned.
     */
    public boolean validate() {
        SQLiteDatabase db = mLecturesDatabase.getReadableDatabase();
        Cursor lectureCursor = null;
        try {
            // Order by "date" column relying on that the date formatted
            // in reverse order: yyyy-MM-dd'T'HH:mm:ssZ
            lectureCursor = db.query(
                    LecturesTable.NAME, null, null, null, null, null, Columns.DATE);

            if (lectureCursor.getCount() == 0) return true;

            // Prepare time range (first day)
            lectureCursor.moveToFirst();
            int dateColumnIndex = lectureCursor.getColumnIndex(Columns.DATE);
            String firstDateString = lectureCursor.getString(dateColumnIndex);
            Date firstDate = DateHelper.getDate(firstDateString, "yyyy-MM-dd");
            String formattedFirstDate = DateHelper.getFormattedDate(firstDate);

            // Prepare time range (last day)
            lectureCursor.moveToLast();
            String lastDateString = lectureCursor.getString(dateColumnIndex);
            Date lastDate = DateHelper.getDate(lastDateString, "yyyy-MM-dd");
            // Increment date by one day since events also happen on the last day
            // and no time information is given - only the pure date.
            lastDate = DateHelper.shiftByDays(lastDate, 1);
            String formattedLastDate = DateHelper.getFormattedDate(lastDate);

            // Check if the time stamp in <date> is within the time range (first : last day)
            // defined by "date" attribute in the <day> nodes.
            lectureCursor.moveToFirst();
            while (!lectureCursor.isAfterLast()) {
                long dateUtcInMilliseconds = lectureCursor.getLong(
                        lectureCursor.getColumnIndex(LecturesTable.Columns.DATE_UTC));
                Date dateUtc = new Date();
                dateUtc.setTime(dateUtcInMilliseconds);

                Date[] dateRange = new Date[]{firstDate, lastDate};
                if (!DateHelper.dateIsWithinRange(dateUtc, dateRange)) {
                    String eventId = lectureCursor.getString(
                            lectureCursor.getColumnIndex(LecturesTable.Columns.EVENT_ID));
                    String formattedDateUtc = DateHelper.getFormattedDate(dateUtc);
                    String errorMessage = "Field <date> " + formattedDateUtc + " of event "
                            + eventId +
                            " exceeds range: [ " + formattedFirstDate + " : " + formattedLastDate
                            + " ]";
                    ValidationError error = new ValidationError(errorMessage);
                    mValidationErrors.add(error);
                }
                lectureCursor.moveToNext();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            if (lectureCursor != null) {
                lectureCursor.close();
            }
            db.close();
        }

        // Evaluate validation
        MyApp.LogDebug(getClass().getName(),
                "Validation result for <date> field: " + mValidationErrors.size() + " errors.");
        return mValidationErrors.isEmpty();
    }

}

@@ -3116,32 +3116,823 @@
 st()) %7B%0A        
+        validateEvent(lectureCursor, firstDate, lastDate,%0A                        formattedFirstDate, formattedLastDate);%0A                lectureCursor.moveToNext();%0A            %7D%0A        %7D catch (SQLException e) %7B%0A            e.printStackTrace();%0A        %7D finally %7B%0A            if (lectureCursor != null) %7B%0A                lectureCursor.close();%0A            %7D%0A            db.close();%0A        %7D%0A%0A        // Evaluate validation%0A        MyApp.LogDebug(getClass().getName(),%0A                %22Validation result for %3Cdate%3E field: %22 + mValidationErrors.size() + %22 errors.%22);%0A        return mValidationErrors.isEmpty();%0A    %7D%0A%0A    private void validateEvent(Cursor lectureCursor, Date firstDate, Date lastDate,%0A                               String formattedFirstDate, String formattedLastDate) %7B%0A
         long dat
@@ -3971,32 +3971,24 @@
 or.getLong(%0A
-        
             
@@ -4058,32 +4058,24 @@
 ));%0A        
-  
-      
 Date dateUtc
@@ -4097,24 +4097,16 @@
         
-     
-   
 dateUtc.
@@ -4134,32 +4134,24 @@
 iseconds);%0A%0A
-        
         Date
@@ -4198,24 +4198,16 @@
 tDate%7D;%0A
-        
         
@@ -4271,32 +4271,24 @@
             
-   
-     
 String event
@@ -4333,32 +4333,24 @@
             
-      
-  
 lectureCurso
@@ -4400,24 +4400,16 @@
 T_ID));%0A
-        
         
@@ -4484,32 +4484,24 @@
             
- 
-       
 String error
@@ -4580,24 +4580,16 @@
         
-        
 + eventI
@@ -4612,24 +4612,16 @@
         
-       
- 
 %22 exceed
@@ -4702,24 +4702,16 @@
         
-        
 + %22 %5D%22;%0A
@@ -4722,24 +4722,16 @@
         
-  
-      
 Validati
@@ -4793,24 +4793,16 @@
         
-     
-   
 mValidat
@@ -4835,509 +4835,9 @@
     
-        %7D%0A                lectureCursor.moveToNext();%0A            %7D%0A        %7D catch (SQLException e) %7B%0A            e.printStackTrace();%0A        %7D finally %7B%0A            if (lectureCursor != null) %7B%0A                lectureCursor.close();%0A            %7D%0A            db.close();%0A        %7D%0A%0A        // Evaluate validation%0A        MyApp.LogDebug(getClass().getName(),%0A                %22Validation result for %3Cdate%3E field: %22 + mValidationErrors.size() + %22 errors.%22);%0A        return mValidationErrors.isEmpty();
+%7D
 %0A   

Improve readability.