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 ExcursionDBHelper {
  static Database? _excursionDB;

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

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

  // The function that helps
  _onCreateExcursion(Database excursionDB, int version) async {
    await excursionDB.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, HinweiseSonstiges TEXT)');
    await excursionDB.execute(
        'CREATE TABLE excursionTemplates (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, HinweiseSonstiges TEXT)');
  }

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

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

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

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

  Future<void> updateExcursion(Map<String, dynamic> excursion) async {
    var excursionDBClient = await excursionDB;

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

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

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

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

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

    await excursionDBClient.insert(
      'excursionTemplates',
      templates,
      // conflictAlgorithm: ConflictAlgorithm.replace,
    );
  }

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

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

  // get the finished entries from db
  Future<List<Map<String, dynamic>>> getExcursionen() async {
    var excursionDBClient = await excursionDB;
    return await excursionDBClient.query('excursion');
  }

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

  // deletes all finished entries from the db LOCALLY
  Future<void> deleteAllExcursionen() async {
    var excursionDBClient = await excursionDB;
    await excursionDBClient.delete('excursion');
  }

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

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

// delete specific excursion
  Future<void> deleteExcursion(String id) async {
    var excursionDBClient = await excursionDB;
    await excursionDBClient.delete(
      'excursion',
      where: 'ID = ?',
      whereArgs: [id],
    );
  }
}
