package findyourfate.com.rahuketupeyarchi;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream ; 
import android.content.Context;  
import android.database.sqlite.SQLiteDatabase; 
import android.database.sqlite.SQLiteOpenHelper;  
public class DatabaseHandler  extends SQLiteOpenHelper { 
    
    private static DatabaseHandler singleton;
    
    public static DatabaseHandler getInstance(final Context context) {
        if (singleton == null) {
            singleton = new DatabaseHandler(context);
        }
        return singleton;
    }
    
    private static SQLiteDatabase mDataBase;  
    private static final String DATABASE_NAME = "rahupeyarchi"; 
    private static final String DATABASE_TABLE_NAME = "rahu";  
    private static final int DATABASE_VERSION = 1;
    public static Context context;
    

    private static final String DATABASE_TABLE_CREATE =
            "CREATE TABLE IF NOT EXISTS " + DATABASE_TABLE_NAME + "(" +
            "ID INTEGER PRIMARY KEY AUTOINCREMENT,"+
            "node TEXT NOT NULL,"+
            "rashi TEXT NOT NULL, entry TEXT NOT NULL, exit TEXT NOT NULL);";
   
    public DatabaseHandler(Context context) {
  	  super(context, DATABASE_NAME, null, DATABASE_VERSION);
  	     try {
  	    	 File dbFile = context.getDatabasePath(DATABASE_NAME);	    	    	
  	    	InputStream is = context.getAssets().open(DATABASE_NAME);	    	      
  	     OutputStream os = new FileOutputStream(dbFile);
  	     byte[] buffer = new byte[1024];
  	     int mLength;
  	     while ((mLength = is.read(buffer))>0)
  	     {
  	         os.write(buffer, 0, mLength);
  	     }
  	     os.flush();
  	     os.close();
  	     is.close();
  	} catch (IOException e) {
  		e.printStackTrace();
  	}
  	}
     
    public SQLiteDatabase openDatabase() {
        File dbFile = context.getDatabasePath(DATABASE_NAME);	         
        
        return SQLiteDatabase.openDatabase(dbFile.getPath(), null, SQLiteDatabase.OPEN_READONLY);
    }
 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 		
		db.execSQL("DROP TABLE IF EXISTS "+DATABASE_TABLE_NAME);
	    onCreate(db);	    	 
	}
	 
	public void open() {	    	 
	 getWritableDatabase(); 
	}    	
	public void onCreate(SQLiteDatabase db) {	    		  
		  db.execSQL(DATABASE_TABLE_CREATE);	    		   
		}
    

    @Override
    public synchronized void close() 
    {
        if(mDataBase != null)
            mDataBase.close();
        super.close();
    }

  
     
    
	 

	 
     

}
