import 'dart:io';

import 'package:aman_kassa_flutter/core/base/base_service.dart';
import 'package:aman_kassa_flutter/core/entity/Goods.dart';
import 'package:aman_kassa_flutter/core/entity/Category.dart';
import 'package:aman_kassa_flutter/core/entity/Service.dart';
import 'package:aman_kassa_flutter/core/entity/Voucher.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 = "AmanFlutterDb.db";
  static final _databaseVersion = 16;

  // 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 $Goog_tableName;');
    await db.execute('DROP TABLE IF EXISTS $Category_tableName;');
    await db.execute('DROP TABLE IF EXISTS $Service_tableName;');
    //await db.execute('DROP TABLE IF EXISTS $Voucher_tableName;');
    log.i('dropped tables');
    if (newVersion > 16) {
      //Не удалять таблицу с чеками
    }

    _onCreate(db, newVersion);
  }

  Future _onCreate(Database db, int version) async {
    log.i('create tables');
    //Goods table
    await db.execute('''
      CREATE TABLE IF NOT EXISTS $Goog_tableName ( 
        $Goog_columnId integer primary key unique, 
        $Goog_columnArticul integer not null,
        $Goog_columnName text not null,
        $Goog_columnPrice real not null,
        $Goog_columnCategoryId integer not null,
        $Goog_columnEan text,
        $Goog_columnAppCompanyId integer,
        $Goog_columnDescription text,
        $Goog_columnShowPrice real,
        $Goog_columnOkei integer,
        $Goog_columnDiscount real
        );
      ''');
    await db.execute('''
      CREATE TABLE IF NOT EXISTS $Category_tableName ( 
        $Category_columnId integer primary key unique, 
        $Category_columnName text not null,
        $Category_columnParentIn integer,
        $Category_columnAppCompanyId integer
        );
      ''');
    //Service
    await db.execute('''
        CREATE TABLE IF NOT EXISTS $Service_tableName ( 
        $Service_columnId integer primary key unique, 
        $Service_columnArticul integer not null,
        $Service_columnName text not null,
        $Service_columnPrice real not null,
        $Service_columnAppCompanyId integer,
        $Service_columnDescription text,
        $Service_columnShowPrice real,
        $Service_columnOkei text,
        $Service_columnDiscount real
        );
      ''');
    //Voucher
    await db.execute('''
      CREATE TABLE IF NOT EXISTS $Voucher_tableName ( 
      $Voucher_columnId integer primary key AUTOINCREMENT, 
      $Voucher_columnName text not null,
      $Voucher_columnTotal real,
      $Voucher_columnData text,
      $Voucher_columnBase64Data text,
      $Voucher_columnDateTime text not null,
      $Service_columnAppCompanyId integer,
      $Voucher_columnKassaId integer,
      $Voucher_columnType text not null,
      $Voucher_columnUrl text
      );
    ''');
  }

  // 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>>> 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) async {
    Database db = await instance.database;
    return await db.query(table, where: where, whereArgs: args);
  }

  // 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 close() async => instance.close();
}
