package com.example.noteszapisdobazy;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.content.ContentValues;

import java.util.ArrayList;
import java.util.List;


public class NotesDbHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "notes.db";
    private static final int DB_VERSION = 1;
    public static final String TABLE_NOTES = "notes";
    public static final String COL_ID = "id";
    public static final String COL_TEXT = "text";
    public NotesDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }
    //------------------------------------------------------------
    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL("CREATE TABLE " + TABLE_NOTES + " (" +
                COL_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                COL_TEXT + " TEXT NOT NULL)");
    }
//-----------------------------------------------------------------
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
        onCreate(db);
    }
//------------------------------------------------------------------
    public long insertNote(String text) {
        ContentValues values = new ContentValues();
        values.put(COL_TEXT, text);
        SQLiteDatabase db = getWritableDatabase();
        return db.insert(TABLE_NOTES, null, values);
    }
//------------------------------------------------------------------
    public List<String> getAllNotes() {
        List<String> notes = new ArrayList<>();
        SQLiteDatabase db = getReadableDatabase();
        Cursor c = db.query(TABLE_NOTES, new String[]{COL_ID, COL_TEXT}, null, null, null, null, COL_ID + " DESC");
        while (c.moveToNext()) {
            long id = c.getLong(c.getColumnIndexOrThrow(COL_ID));
            String text = c.getString(c.getColumnIndexOrThrow(COL_TEXT));
            notes.add(id + ": " + text);
        }
        c.close();
        return notes;
    }
}
