import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:gymlink_module_web/interfaces/items.dart';
import 'package:gymlink_module_web/providers/main.dart';
import 'package:http/http.dart' as http;
import 'package:provider/provider.dart';

Future<List<GymItem>> getItems(BuildContext context) async {
  final token = context.read<GymLinkProvider>().token;
  if (token != '') {
    final Uri url =
        Uri.http('gymlink.freemyip.com:8080', 'api/product/get-list');
    try {
      final response = await http.get(url, headers: {
        'Authorization': 'Bearer $token',
      });
      if (response.statusCode == 200) {
        final data =
            jsonDecode(utf8.decode(response.bodyBytes)) as List<dynamic>;
        final items = data.map((e) => GymItem.fromJson(e)).toList();
        return items;
      }
      throw Error();
    } catch (e) {
      debugPrint('error: $e');
      return await Future.delayed(
          const Duration(seconds: 5), () => getItems(context));
    }
  }
  context.read<GymLinkProvider>().onError();
  return [];
}
