package com.example.calendaryapp;


import android.content.Context;
import android.os.AsyncTask;

import androidx.annotation.NonNull;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.sqlite.db.SupportSQLiteDatabase;

@Database(entities = {Note.class}, version = 3, exportSchema = false)
public abstract class NoteDatabase extends RoomDatabase {
    //database  es abstracto y la biblioteca room se encarga de implementarla
    private static NoteDatabase instance;
    public abstract NoteDao noteDao();
    public static synchronized NoteDatabase getInstance(Context context){
        if (instance ==null){
            instance = Room.databaseBuilder(context.getApplicationContext(),NoteDatabase.class,
                    "note_database")
                    .fallbackToDestructiveMigration()
                    .addCallback(roomCallback) //cuando la instancia sea creada por primera vez se agregaran elementos a la base de datos
                    .build();

        }

        return instance;

    }
    private static RoomDatabase.Callback roomCallback = new RoomDatabase.Callback(){

        @Override
        public void onCreate(@NonNull SupportSQLiteDatabase db) {
            super.onCreate(db);
            new PopulateDbAsyncTask(instance).execute();
        }
    };

    private static class PopulateDbAsyncTask extends AsyncTask<Void, Void, Void> {
        //se crea la base de datos y se llena con cosas
        private NoteDao noteDao; //Como es una clase estatico se pasa la base de datos de esta forma

        private PopulateDbAsyncTask(NoteDatabase db) {
            noteDao = db.noteDao();
        }

        @Override
        protected Void doInBackground(Void... voids) {
            noteDao.insert(new Note("ELO329", "Programacion Orientada a Objetos", 1,"1-2","8:00-9:00","C-345"));
            noteDao.insert(new Note("ELO322", "Redes de PC", 2,"3-4","9:45-11:15","C345"));
            noteDao.insert(new Note("ELO293 3", "Probabilidad y estadistica", 3,"5-6","11:30-13:00","C322"));
            return null;
        }
    }

}
