import 'dart:async';
import 'package:flutter/widgets.dart';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';

Future<void> deleteDb() async {
    final path = join(await getDatabasesPath(), 'capsule.db');
    deleteDatabase(path);
}

Future<Database> getDatabaseConnection() async {
    WidgetsFlutterBinding.ensureInitialized();

    final path = join(await getDatabasesPath(), 'capsule.db');

    final database = openDatabase(
            path,
            onCreate: (db, version) async {
                await db.execute(
                        '''
                        CREATE TABLE IF NOT EXISTS friends(
                                id TEXT PRIMARY KEY,
                                user_id TEXT,
                                username TEXT,
                                friend_id TEXT,
                                symmetric_key TEXT,
                                asymmetric_public_key TEXT,
                                accepted_at TEXT
                        );
                        ''');

                await db.execute(
                        '''
                        CREATE TABLE IF NOT EXISTS conversations(
                                id TEXT PRIMARY KEY,
                                user_id TEXT,
                                symmetric_key TEXT,
                                admin INTEGER,
                                name TEXT,
                                two_user INTEGER,
                                status INTEGER,
                                is_read INTEGER,
                                file TEXT
                        );
                        ''');

                await db.execute(
                        '''
                        CREATE TABLE IF NOT EXISTS conversation_users(
                                id TEXT PRIMARY KEY,
                                user_id TEXT,
                                conversation_id TEXT,
                                username TEXT,
                                association_key TEXT,
                                admin INTEGER,
                                asymmetric_public_key TEXT
                        );
                        ''');

                await db.execute(
                        '''
                        CREATE TABLE IF NOT EXISTS messages(
                                id TEXT PRIMARY KEY,
                                symmetric_key TEXT,
                                user_symmetric_key TEXT,
                                data TEXT,
                                file TEXT,
                                sender_id TEXT,
                                sender_username TEXT,
                                association_key TEXT,
                                created_at TEXT,
                                failed_to_send INTEGER
                        );
                        ''');

            },
      version: 2,
    );

    return database;
}
