import 'dart:io';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:gifunavi/model/gps_data.dart';
import 'package:sqflite/sqflite.dart';

class GpsDatabaseHelper {
  GpsDatabaseHelper._privateConstructor();
  static final GpsDatabaseHelper instance =
      GpsDatabaseHelper._privateConstructor();
  static Database? _database;
  Future<Database> get database async => _database ??= await _initDatabase();

  Future<Database> _initDatabase() async {
    Directory documentDirectory = await getApplicationDocumentsDirectory();
    String path = join(documentDirectory.path, 'rog.db');
    // return  await openDatabase(
    //   path,
    //   version: 1,
    //   onCreate: _onCreate,
    // );
    return openDatabase(
        join(
          await getDatabasesPath(),
          'gps.db',
        ),
        version: 1,
        onCreate: _onCreate);
  }

  Future _onCreate(Database db, int version) async {
    await db.execute('''
    CREATE TABLE gps(
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      team_name TEXT,
      event_code TEXT,
      lat REAL, 
      lon REAL,
      is_checkin int,
      created_at INTEGER,
      is_synced INTEGER DEFAULT 0
    )
    ''');
  }

  Future<int> insertGps(GpsData gps) async {
    try {
      //print("---- try insering ${gps.toMap()}");
      Database db = await instance.database;
      int? nextOrder =
          Sqflite.firstIntValue(await db.rawQuery('SELECT MAX(id) FROM gps'));
      nextOrder = nextOrder ?? 0;
      nextOrder = nextOrder + 1;
      gps.id = nextOrder;
      //print("---- insering ${gps.toMap()}");
      int res = await db.insert(
        'gps',
        gps.toMap(),
        conflictAlgorithm: ConflictAlgorithm.replace,
      );
      //print("------ database helper insert $res-----------::::::::");
      return res;
    } catch (err) {
      print("------ error $err-----------::::::::");
      return -1;
    }
  }

  Future<List<GpsData>> getGPSData(String teamName, String eventCode) async {
    Database db = await instance.database;
    var gpss = await db.query('gps',
        where: "team_name = ? and event_code = ?",
        whereArgs: [teamName, eventCode],
        orderBy: 'created_at');
    List<GpsData> gpsDatas =
        gpss.isNotEmpty ? gpss.map((e) => GpsData.fromMap(e)).toList() : [];
    //print("--------- db list $gpsDatas");
    return gpsDatas;
  }

  Future<List<GpsData>> getUnsyncedGPSData(
      String teamName, String eventCode) async {
    Database db = await instance.database;
    var gpss = await db.query('gps',
        where: 'team_name = ? and event_code = ? and is_synced = 0',
        whereArgs: [teamName, eventCode],
        orderBy: 'created_at');
    return gpss.isNotEmpty ? gpss.map((e) => GpsData.fromMap(e)).toList() : [];
  }

  Future<void> setSyncData(List<GpsData> data) async {
    Database db = await instance.database;
    for (var record in data) {
      await db.update(
        'gps',
        {'is_synced': 1},
        where: 'id = ?',
        whereArgs: [record.id],
      );
    }
  }
}
