import 'dart:io';

import 'package:satu/core/base/base_service.dart';
import 'package:satu/core/entity/Category.dart';
import 'package:satu/core/entity/Goods.dart';
import 'package:satu/core/entity/Transaction.dart';
import 'package:sqflite/sqflite.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';

class DbService extends BaseService {
  static final _databaseName = "AmanSatuDb.db";
  static final _databaseVersion = 1;

  // make this a singleton class
  DbService._privateConstructor();

  static final DbService instance = DbService._privateConstructor();

  // only have a single app-wide reference to the database
  static Database? _database;

  Future<Database?> get database async {
    if (_database != null) return _database;
    // lazily instantiate the db the first time it is accessed
    _database = await _initDatabase();
    return _database;
  }

  // this opens the database (and creates it if it doesn't exist)
  _initDatabase() async {
    Directory documentsDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentsDirectory.path, _databaseName);
    return await openDatabase(path,
        version: _databaseVersion, onUpgrade: _onUpdate, onCreate: _onCreate);
  }

  Future _onUpdate(Database db, int oldVersion, int newVersion) async {
    log.i('update from $oldVersion to $newVersion');
    //Goods table
    await db.execute('DROP TABLE IF EXISTS $GoodTableName;');
    await db.execute('DROP TABLE IF EXISTS $CategoryTableName;');
    //await db.execute('DROP TABLE IF EXISTS $Voucher_tableName;');
    log.i('dropped tables');
    _onCreate(db, newVersion);
  }

  Future _onCreate(Database db, int version) async {
    log.i('create tables');
    //Goods table
    await db.execute('''
      CREATE TABLE IF NOT EXISTS $GoodTableName ( 
        $GoodColumnId integer primary key unique, 
        $GoodColumnArticul integer not null,
        $GoodColumnName text not null,
        $GoodColumnPrice real not null,
        $GoodColumnCategoryId integer not null,
        $GoodColumnEan text,
        $GoodColumnAppCompanyId integer,
        $GoodColumnOptPrice real,
        $GoodColumnBasePrice real,
        $GoodColumnDivisible integer,
        $GoodColumnUpdatedAt text not null
        );
      ''');
    await db.execute('''
      CREATE TABLE IF NOT EXISTS $CategoryTableName ( 
        $CategoryColumnId integer primary key unique, 
        $CategoryColumnName text not null,
        $CategoryColumnParentIn integer,
        $CategoryColumnAppCompanyId integer,
        $CategoryColumnUpdatedAt text not null
        );
      ''');
    await db.execute('''
      CREATE TABLE IF NOT EXISTS $TransactionTableName ( 
        $TransactionColumnId integer primary key autoincrement, 
        $TransactionColumnUuid text,
        $TransactionColumnType integer not null,
        $TransactionColumnAppCompanyId integer not null,
        $TransactionColumnStatus integer not null,
        $TransactionColumnData text,
        $TransactionColumnCreatedAt text not null
        );
      ''');
  }

  // Inserts a row in the database where each key in the Map is a column name
  // and the value is the column value. The return value is the id of the
  // inserted row.
  Future<int> insert(String table, Map<String, dynamic> row) async {
    Database? db = await instance.database;
    return await db!.insert(table, row);
  }

  // All of the rows are returned as a list of maps, where each map is
  // a key-value list of columns.
  Future<List<Map<String, dynamic>>> queryAllRows(String table) async {
    Database? db = await instance.database;
    return await db!.query(table);
  }

  Future<List<Map<String, dynamic>>> queryRaw(String sql, List<dynamic> args) async {
    Database? db = await instance.database;
    return await db!.rawQuery(sql, args );
  }

  Future<List<Map<String, dynamic>>> queryAllRowsOrderBy(String table, String orderBy) async {
    Database? db = await instance.database;
    return await db!.query(table, orderBy: orderBy);
  }

  Future<List<Map<String, dynamic>>> queryRowsWithWhere(
      String table, String where, List<dynamic> args, { String? orderBy }) async {
    Database? db = await instance.database;
    return await db!.query(table, where: where, whereArgs: args, orderBy: orderBy);
  }

  // All of the methods (insert, query, update, delete) can also be done using
  // raw SQL commands. This method uses a raw query to give the row count.
  Future<int?> queryRowCount(String table) async {
    Database? db = await instance.database;
    return Sqflite.firstIntValue(
        await db!.rawQuery('SELECT COUNT(*) FROM $table'));
  }

  // We are assuming here that the id column in the map is set. The other
  // column values will be used to update the row.
  Future<int> update(String table, Map<String, dynamic> row) async {
    Database? db = await instance.database;
    int id = row['id'];
    return await db!.update(table, row, where: 'id = ?', whereArgs: [id]);
  }

  // Deletes the row specified by the id. The number of affected rows is
  // returned. This should be 1 as long as the row exists.
  Future<int> delete(String table, int id) async {
    Database? db = await instance.database;
    return await db!.delete(table, where: 'id = ?', whereArgs: [id]);
  }

  Future<int> deleteAll(String table) async {
    Database? db = await instance.database;
    return await db!.delete(table);
  }

  Future<int> deleteByWhere(String table, String where, List<dynamic> args) async {
    Database? db = await instance.database;
    return await db!.delete(table, where: where, whereArgs: args);
  }

  Future close() async => instance.close();
}
