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 PlaceDBHelper {
  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 AUTOINCREMENT, CID TEXT, Standort TEXT, Rudel TEXT, Datum DATE, Adresse1 TEXT, Adresse2 TEXT, Adresse3 TEXT, BLand TEXT, Lkr TEXT, BeiOrt TEXT, OrtInfo TEXT, Status TEXT, FFTyp TEXT, FotoFilm TEXT, MEZ TEXT, Platzung TEXT, KSchloNr TEXT, KontDat DATE, Betreuung TEXT, AbbauDat DATE, Auftrag TEXT, KontAbsp TEXT, SonstBem TEXT, FKontakt1 TEXT, FKontakt2 TEXT, FKontakt3 TEXT,  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 placeTemplates (ID INTEGER PRIMARY KEY AUTOINCREMENT, CID TEXT, Standort TEXT, Rudel TEXT, Datum DATE, Adresse1 TEXT, Adresse2 TEXT, Adresse3 TEXT, BLand TEXT, Lkr TEXT, BeiOrt TEXT, OrtInfo TEXT, Status TEXT, FFTyp TEXT, FotoFilm TEXT, MEZ TEXT, Platzung TEXT, KSchloNr TEXT, KontDat DATE, Betreuung TEXT, AbbauDat DATE, Auftrag TEXT, KontAbsp TEXT, SonstBem TEXT, FKontakt1 TEXT, FKontakt2 TEXT, FKontakt3 TEXT, KTage1 INTEGER, KTage2 INTEGER, ProtoAm DATE, IntKomm TEXT, DECLNG DECIMALS(4,8), DECLAT DECIMALS(4,8))');
    await placeDB.execute(
        'CREATE TABLE excursion (ID INTEGER PRIMARY KEY AUTOINCREMENT, Datum TEXT, Rudel TEXT, Teilnehmer TEXT, Jahr TEXT, Mjahr TEXT, Monat INTEGER, Saison TEXT, Dauer TEXT, BLjahr TEXT, BLand, TEXT, Lkr TEXT, BeiOrt TEXT, Wetter TEXT, Temperat TEXT, RegenVor TEXT, KmAuto TEXT, KmFuss TEXT, KmRad TEXT, KmTotal TEXT, KmAuProf TEXT, KmFuProz TEXT, KmRaProz TEXT, SpGut TEXT, SpSchlecht TEXT, SpurFund TEXT, SpurLang TEXT, SpurTiere Text, SpSicher TEXT, WelpenSp TEXT, WelpenAnz TEXT, WpSicher TEXT, LosungGes TEXT, LosunAnz TEXT, LosunGen TEXT, UrinAnz TEXT, UrinGen TEXT, OestrAnz TEXT, OestrGen TEXT, HaarAnz TEXT, HaarGen TEXT, LosungKm TEXT, GenetiKm TEXT, Hinweise TEXT, Bemerk TEXT, IntKomm TEXT, BimaNr TEXT, BimaName TEXT, BimaNutzer TEXT, BimaAGV TEXT, FallNum INTEGER, MHund TEXT, MLeine TEXT, LogDat TEXT)');
  }

// Function to add a finished entry and return its ID
  Future<int> addPlace(Map<String, dynamic> place) async {
    var placeDBClient = await placeDB;
    final existingID = await placeDBClient.query(
      'place',
      where: 'ID = ?',
      whereArgs: [place['ID']],
    );

    if (existingID.isNotEmpty) {
      updatePlace(place);
      return existingID.first['ID'] as int; // Return existing ID
    }

    int id = await placeDBClient.insert(
      'place',
      place,
      //conflictAlgorithm: ConflictAlgorithm.replace,
    );

    return id; // Return the ID of the newly inserted entry
  }

  Future<void> updatePlace(Map<String, dynamic> place) async {
    var placeDBClient = await placeDB;

    await placeDBClient
        .update('place', place, where: "ID = ?", whereArgs: [place['ID']]);
  }

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

    await placeDBClient.update('place', {'Sent': 1},
        where: 'ID = ?', whereArgs: [id]);
  }

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

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

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

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

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

  // 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('placeTemplates');
  }

  // 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('placeTemplates');
  }

  // delete specific template
  Future<void> deleteTemplate(String id) async {
    var placeDBClient = await placeDB;
    await placeDBClient.delete(
      'placeTemplates',
      where: 'ID = ?',
      whereArgs: [id],
    );
  }

// delete specific place
  Future<void> deletePlace(String id) async {
    var placeDBClient = await placeDB;
    await placeDBClient.delete(
      'place',
      where: 'ID = ?',
      whereArgs: [id],
    );
  }
}
