import 'dart:convert';
import 'dart:io';

import 'package:http/http.dart' as http;
import 'package:mhunt_launcher/Backend/Structures.dart';
import 'package:path_provider/path_provider.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'DebugHelper.dart';

class Backend{
  static const String API_ENDPOINT = "https://vps.playpoolstudios.com/metahunt/api/launcher/";

  static List<GameData> Games = [
      GameData(0,"mhunt","Metahunt", "High-Stake Battle Royale game with Play to earn abilities", "images/mhunt_thumbnail.png", true,"CRPB.exe"),
      GameData(1,"pop3d","Pop3D", "a game I dont know much about xD", "images/pop3d_thumbnail.png", false, "pop3d.exe"),
  ];
  static SharedPreferences? prefs;
  static Directory? docPath;

  static String Username="";

  static Future<bool> Login(String username, String password) async{
    var loginResponse = null;
    init();
    try {
      loginResponse = (await http.post(Uri.parse('${API_ENDPOINT}login.php'),
          body: <String, String>{"username": username, "password": password}));
      Debug.LogResponse(loginResponse.body.toString(),src: '${API_ENDPOINT}login.php');

      try {
        Username=username;
        return true;
      } catch (e) {
      }
    } catch (e) {
      Debug.LogError("Error while login $e");
    }
    return false;
  }

  static void init()async{
    prefs = await SharedPreferences.getInstance();
    docPath = await getDownloadsDirectory();
  }

  static Future<bool> Register(String username, String password) async{
    var loginResponse = null;
    init();

    try {
      loginResponse = (await http.post(Uri.parse('${API_ENDPOINT}register.php'),
          body: <String, String>{"username": username, "password": password}));
      Debug.LogResponse(loginResponse.body.toString(),src: '${API_ENDPOINT}register.php');

      try {
        return true;
      } catch (e) {
      }
    } catch (e) {
      Debug.LogError("Error while login $e");
    }

    return false;
  }

  static Future<List<LeaderboardEntry>> GetLeaderboard(String gameCode) async{
    String url = '${API_ENDPOINT}/${gameCode}/get_leaderboard.php';
    var leaderboardResponse = await http.get(Uri.parse(url));

    return LeaderboardEntry.listFromJson(leaderboardResponse.body);
  }

  static Future<List<Map<String,dynamic>>> GetNewsForGame(int gameId)async{
    String url = '${API_ENDPOINT}${Games[gameId].code}/get_news.php';
    try{
      var res = await http.get(Uri.parse(url));
      List<dynamic> jsonList = jsonDecode(res.body);
      List<Map<String,dynamic>> output = [];
      jsonList.forEach((element) {
        output.add(element as Map<String,dynamic>);
      });

      return output;
    }catch(e){
      Debug.LogError(e);
    }
    
    return [{}];
  }

  static Future<Map<String,dynamic>> GetUserStatsForGame(int gameId) async{
    var loginResponse = null;
    init();

    try {
      String url = '${API_ENDPOINT}${Games[gameId].code}/get_user_stats.php';
      loginResponse = (await http.post(Uri.parse(url),
          body: <String, String>{"username": prefs!.getString("username") ?? "test"}));
      Debug.LogResponse(loginResponse.body.toString(),src: url);

      return jsonDecode(loginResponse.body);
    } catch (e) {
      Debug.LogError("Error while login $e");
    }

    return {};
  }
}


class GameData{
  int id;
  String code;
  String name;
  String description;
  String imagePath;
  bool isAvailable;
  String exeName;

  GameData(this.id,this.code,this.name,this.description,this.imagePath,this.isAvailable,this.exeName);
}