import 'dart:async';
import 'dart:io' as io;

import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:elektronika/app/data/models/models.dart';
import 'package:sqflite/sqflite.dart';

class DBHelper {
  Database? _db;

  static const String ID = 'id';
  static const String KEYWORD = 'keyword';
  static const String FIELD = 'field';

  static const String TABLE = 'history';
  static const String DB_NAME = 'search_history.db';

  Future<Database?> get db async {
    if (_db != null) {
      return _db;
    }
    _db = await initDb();
    return _db;
  }

  Future<Database> initDb() async {
    io.Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, DB_NAME);
    var db = await openDatabase(path, version: 1, onCreate: _onCreate);
    return db;
  }

  Future<void> _onCreate(Database db, int version) async {
    await db.execute('CREATE TABLE IF NOT EXISTS $TABLE ($ID INTEGER PRIMARY KEY AUTOINCREMENT,  $KEYWORD TEXT,$FIELD TEXT )');
  }

  Future<void> save(SearchHistory searchHistory) async {
    var dbClient = await db;
    if (dbClient != null) await dbClient.insert(TABLE, searchHistory.toJson());
  }

  Future<List<SearchHistory>> getSearchHistory() async {
    var dbClient = await db;
    if (dbClient != null) {
      List<Map> maps = await dbClient.rawQuery('SELECT * FROM $TABLE ORDER BY $ID DESC;');
      List<SearchHistory> products = [];
      if (maps.length > 0) {
        for (int i = 0; i < maps.length; i++) {
          products.add(SearchHistory.fromJson(maps[i]));
        }
      }
      return products;
    }
    return [];
  }

  Future<void> resetDb() async {
    var dbClient = await db;
    if (dbClient != null) {
      await dbClient.delete(TABLE);
      // reset id
      await dbClient.execute('UPDATE sqlite_sequence SET seq = (SELECT MAX($ID) FROM $TABLE) WHERE name="$TABLE"');
    }
  }

  Future close() async {
    var dbClient = await db;
    if (dbClient != null) dbClient.close();
  }
}


