import 'dart:convert';

import 'package:fhub/backend/helpers.dart';
import 'package:http/http.dart' as http;
import 'DebugHelper.dart';

class DataManager{
  static const String API_ENDPOINT = "http://vps.playpoolstudios.com/faucet/api/";
  static Map<String,String> Settings = {};

  static List<dynamic> AllGames = [];
  static List<dynamic> FeaturedGames = [];
  static List<dynamic> LinkedGamesJson = [];
  static List<dynamic> NonLinkedGamesJson = [];

  static List<List<dynamic>> Challenges= [];

  static dynamic UserJson;

  static Future<bool> Init() async{
    bool isSettingsDone = await GetSettings();
    bool isGamesDone = await GetGames();
    
    return isSettingsDone && isGamesDone;
  }

  static Future<void> GetGamesProgress() async{
    FilterLinkedGames();
    await GetChallenges();

  }

  static void FilterLinkedGames(){
    LinkedGamesJson = [];
    NonLinkedGamesJson = [];

    List<Map<String, dynamic>> linkedGames = jsonDecode(
        UserJson['linkedGames']).cast<Map<String, dynamic>>();

    AllGames.forEach((element) {
      bool foundLink = false;
      for (var linkedGame in linkedGames) {
        int gid = linkedGame["game_id"];
        int id = int.parse(element['id']);
        if (gid == id) {
          LinkedGamesJson.add(element);
          foundLink = true;
          break;
        }
      }

      if (!foundLink) {
        NonLinkedGamesJson.add(element);
      }
    });
  }

  static Future<bool> GetSettings() async{
    try {
      var response = (await http.post(Uri.parse('${API_ENDPOINT}get_settings.php')));

      Debug.LogResponse("settings: ${response.body}");

      List jsonList = jsonDecode(response.body.toString());
      jsonList.forEach((jsonItem) {
        Settings[jsonItem['id']] = jsonItem['value'];
      });

      return true;
    } catch (e) {
      Debug.LogError("Error while gettings settings :  $e");
      return false;
    }
  }
  
  static Future<bool>GetGames() async{
    try {
      var response = (await http.post(Uri.parse('${API_ENDPOINT}get_games.php')));

      Debug.LogResponse("Games: ${response.body}");
      AllGames=[];
      FeaturedGames = [];
      List<String> games = response.body.toString().split("<td>");
      List<String> featuredGames = Settings["featured_games"].toString().split(',');
      games.forEach((game) {
        dynamic Json = jsonDecode(game);
        String id = Json['id'];
        AllGames.add(Json);
        print(Json);

        if(featuredGames.contains(id)){
          FeaturedGames.add(Json);
        }
      });
      
      return true;
    } catch (e) {
      Debug.LogError("Error while loading games :  $e");
      
      return false;
    }
  }

  static Future<bool> GetChallenges() async{
    var response = null;

    List<List<dynamic>> _Challenges = [];
    double _currentEarnings = 0;
    for (var value in LinkedGamesJson) {
      try {
        Debug.Log("game_code : ${value['code']}, id: ${UserJson['id']}");
        response = (await http.post(
            Uri.parse('${API_ENDPOINT}get_challenges.php'),
            body: <String, String>{
              "game_code": value['code'],
              "id": UserJson['id']
            }));
        Debug.Log("Challenges response: " +response.body.toString());
        List<dynamic> newChallenges = jsonDecode(response.body.toString());

        _Challenges.add(newChallenges);
      } catch (e) {
        Debug.LogError("Error while fetching challenges $e");
        return false;
      }
    }

    Challenges = _Challenges;
    return true;
  }
}