import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:io' as io;
import 'package:path/path.dart';

// * Gives the complete functionality for the databases
// ! functions may not be named complete correctly

class DBHelper {
  static Database? _placeDB;


  // checks if the databses are existing and creates them with the initPlaceDatabase function if not
  Future<Database> get placeDB async {
    if (_placeDB != null) {
      return _placeDB!;
    }
   _placeDB = await initPlaceDatabase();
    return _placeDB!;
  }

  // Creates the databases with help from the _onCreatePlace function
  initPlaceDatabase() async {
    io.Directory documentsDirectory = await getApplicationCacheDirectory();
    String path = join(documentsDirectory.path, 'placeDB.db');
    var placeDB =
        await openDatabase(path, version: 1, onCreate: _onCreatePlace);
    return placeDB;
  }

  // The function that helps
  _onCreatePlace(Database placeDB, int version) async {
    await placeDB.execute(
      'CREATE TABLE place (id INTEGER PRIMARY KEY, CID TEXT UNIQUE, Standort TEXT, Rudel TEXT, Datum DATE, Adresse1 TEXT, Adresse2 TEXT, Adresse3 TEXT, BLand TEXT, Lkr TEXT, BeiOrt TEXT, OrtInfo TEXT, Status TEXT, STTyp TEXT, FFTyp TEXT, FotoFilm TEXT, MEZ TEXT, Platzung TEXT, KSchloNr TEXT, Bearsafe TEXT, KontDat DATE, Betreuung TEXT, AbbauDat DATE, Auftrag TEXT, KontAbsp TEXT, SonstBem TEXT, FKontakt1 TEXT, FKontakt2 TEXT, FKontakt3 TEXT, AusVon DATE, AusBis DATE, KTage1 INTEGER, KTage2 INTEGER, ProtoAm DATE, IntKomm TEXT, DECLNG DECIMALS(4,8), DECLAT DECIMALS(4,8), Sent INTEGER DEFAULT 0)');
    await placeDB.execute(
        'CREATE TABLE templates (id INTEGER PRIMARY KEY, CID TEXT UNIQUE, Standort TEXT, Rudel TEXT, Datum DATE, Adresse1 TEXT, Adresse2 TEXT, Adresse3 TEXT, BLand TEXT, Lkr TEXT, BeiOrt TEXT, OrtInfo TEXT, Status TEXT, STTyp TEXT, FFTyp TEXT, FotoFilm TEXT, MEZ TEXT, Platzung TEXT, KSchloNr TEXT, Bearsafe TEXT, KontDat DATE, Betreuung TEXT, AbbauDat DATE, Auftrag TEXT, KontAbsp TEXT, SonstBem TEXT, FKontakt1 TEXT, FKontakt2 TEXT, FKontakt3 TEXT, AusVon DATE, AusBis DATE, KTage1 INTEGER, KTage2 INTEGER, ProtoAm DATE, IntKomm TEXT, DECLNG DECIMALS(4,8), DECLAT DECIMALS(4,8))');
  }


  // Function to add a finished entrie
  Future<void> addPlace(Map<String, dynamic> place) async {
    var placeDBClient = await placeDB;

    // gets an camid if it already exists
    final existingCID = await placeDBClient.query(
      'place',
      where: 'CID = ?',
      whereArgs: [place['CID']],
    );

    // checks if the camid var from before is empty to avoid double entries
    if (existingCID.isNotEmpty) {
      return;
    }

    // inserts the entrie in the database
    await placeDBClient.insert(
      'place',
      place,

      // replaces the entrie with the new onw if a unique value exists and conflicts
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  // function to update the sent value
  Future<void> updateSent() async {
    var placeDBClient = await placeDB;

    placeDBClient.update('place', true as Map<String, Object?>, where: 'CID = ?', whereArgs: ['CID']);
  }

  // same thing as before but with templatews
  Future<void> addTemplate(Map<String, dynamic> templates) async {
    var placeDBClient = await placeDB;

    final existingCID = await placeDBClient.query(
      'templates',
      where: 'CID = ?',
      whereArgs: [templates['CID']],
    );
    if (existingCID.isNotEmpty) {
      return;
    }

    await placeDBClient.insert(
      'templates',
      templates,
      conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

  // Updates a existing template
  Future<void> updateTemplate(Map<String, dynamic> template) async {
    var placeDBClient = await placeDB;

    await placeDBClient.update(
      'templates',
      template,
      where: "CID = ?",
      whereArgs: [template['CID']],
    );
  }


  // get the finished entries from db
  Future<List<Map<String, dynamic>>> getPlace() async {
    var placeDBClient = await placeDB;
    return await placeDBClient.query('place');
  }

  // get the finished templates from db
  Future<List<Map<String, dynamic>>> getTemplates() async {
    var placeDBClient = await placeDB;
    return await placeDBClient.query('templates');
  }

  // deletes all finished entries from the db LOCALLY
  Future<void> deleteAllPlaces() async {
    var placeDBClient = await placeDB;
    await placeDBClient.delete('place');
  }

  // deletes all templates from the db LOCALLY
  Future<void> deleteAllTemplates() async {
    var placeDBClient = await placeDB;
    await placeDBClient.delete('templates');
  }
}
