import 'dart:async'; import 'package:path/path.dart'; import 'package:smoke_cess_app/models/mood.dart'; import 'package:sqflite/sqflite.dart'; // ignore: depend_on_referenced_packages import 'package:path_provider/path_provider.dart'; import 'dart:io'; import '../models/sleep.dart'; class DatabaseService { DatabaseService._privateConstructor(); static final DatabaseService instance = DatabaseService._privateConstructor(); static Database? _database; Future get database async => _database ??= await _initDatabase(); Future _initDatabase() async { Directory documentsDirectory = await getApplicationDocumentsDirectory(); String path = join(documentsDirectory.path, 'database.db'); return await openDatabase(path, version: 1, onCreate: _onCreate, onOpen: _createTablesIfNotExists); } Future _onCreate(Database db, int version) async { await _createTablesIfNotExists(db); } Future _createTablesIfNotExists(Database db) async { await db.execute(_createMoodTable); await db.execute(_createSleepTable); await db.execute(_createRelapseTable); await db.execute(_createWorkoutTable); } //TODO use generic function? Future> getMoodRecords() async { Database db = await instance.database; var moodRecords = await db.query('mood'); List moodList = moodRecords.isNotEmpty ? moodRecords.map((e) => Mood.fromDatabase(e)).toList() : []; return moodList; } Future> getSleepRecords() async { Database db = await instance.database; var sleepRecords = await db.query('sleep'); List sleepList = sleepRecords.isNotEmpty ? sleepRecords.map((e) => Sleep.fromDatabase(e)).toList() : []; return sleepList; } Future addMood(Mood mood) async { Database db = await instance.database; return await db.insert('mood', mood.toMap()); } Future addSleep(Sleep sleep) async { Database db = await instance.database; return await db.insert('sleep', sleep.toMap()); } } String _createMoodTable = ''' CREATE TABLE IF NOT EXISTS mood( id INTEGER PRIMARY KEY, value INTEGER, date TEXT, comment TEXT ) '''; String _createSleepTable = ''' CREATE TABLE IF NOT EXISTS sleep( id INTEGER PRIMARY KEY, value INTEGER, date TEXT, comment TEXT, sleptAtHour INTEGER, sleptAtMinute INTEGER, wokeUpAtHour INTEGER, wokeUpAtMinute INTEGER ) '''; String _createRelapseTable = ''' CREATE TABLE IF NOT EXISTS relapse( id INTEGER PRIMARY KEY, date TEXT, comment TEXT, reason TEXT ) '''; String _createWorkoutTable = ''' CREATE TABLE IF NOT EXISTS workout( id INTEGER PRIMARY KEY, date TEXT, motivationBefore INTEGER, commentBefore TEXT, motivationAfter INTEGER, commentAfter TEXT, completed INTEGER ) ''';