mirrored_repositories/flutter-sqlite-todo
// frozen_string_literal: true

import 'package:flutter/foundation.dart';
import 'package:sqflite/sqflite.dart' as sql;

class SQLHelper {
  static Future<void> createTables(sql.Database database) async {
    await database.execute("""
      CREATE TABLE items(
        id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
        title TEXT,
        description TEXT,
        createdAt TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
      )
    """);
  }

  // Establish database connection
  static Future<sql.Database> db() async {
    return sql.openDatabase(
      'kindacode.db',
      version: 1,
      onCreate: (sql.Database database, int version) async {
        await createTables(database);
      }
    );
  }

  // Create a new item
  // params:  title(string), description (string)
  static Future<int> createItem(String title, String? description) async {
    final db = await SQLHelper.db();

    final data = {
      'title': title,
      'description': description
    };

    final id = await db.insert('items', data,
    conflictAlgorithm: sql.ConflictAlgorithm.replace);
    return id;
  }

  // Read all items
  // params: none
  static Future<List<Map<String, dynamic>>> getItems() async {
    final db = await SQLHelper.db();
    return db.query('items', orderBy: 'id');
  }

  // Read a single item by id
  // params: id(int)
  static Future<List<Map<String, dynamic>>> getItem(int id) async  {
    final db = await SQLHelper.db();
    return db.query('items', where: 'id = ?', whereArgs: [id], limit: 1);
  }

  // Update a single item by id
 // params: id(int), title(string), description(string)
 static Future<int> updateItem(int id, String title, String? description) async  {
    final db = await SQLHelper.db();

    final data = {
      'title': title,
      'description': description,
      'createdAt': DateTime.now().toString()
    };

    final result = await db.update('items', data,
    where: 'id = ?', whereArgs: [id]);

    return result;
 }

  // Delete a single item by id
  // params: id(int)
  static Future<void> deleteItem(int id) async {
    final db = await SQLHelper.db();

    try {
      await db.delete("items", where: "id = ?", whereArgs: [id]);
    } catch (err) {
      debugPrint("Something went wrong when deleting an item $err");
    }
  }
}