import 'dart:convert';
import 'package:flutter/services.dart';
import '../model/entity.dart';

class PlayerTemplate {
  final String id;
  final String name;
  final String description;
  final int baseHp;
  final int baseAtk;
  final int baseDefense;
  final int baseDodge; // New field
  final String? image;

  const PlayerTemplate({
    required this.id,
    required this.name,
    required this.description,
    required this.baseHp,
    required this.baseAtk,
    required this.baseDefense,
    this.baseDodge = 1, // Default 1
    this.image,
  });

  factory PlayerTemplate.fromJson(Map<String, dynamic> json) {
    return PlayerTemplate(
      id: json['id'],
      name: json['name'],
      description: json['description'],
      baseHp: json['baseHp'],
      baseAtk: json['baseAtk'],
      baseDefense: json['baseDefense'],
      baseDodge: json['baseDodge'] ?? 1, // Parse with default
      image: json['image'],
    );
  }

  Character createCharacter() {
    return Character(
      name: name,
      maxHp: baseHp,
      atk: baseAtk,
      baseDefense: baseDefense,
      baseDodge: baseDodge, // Use template value
      armor: 0,
      image: image, // Pass image path
    );
  }
}

class PlayerTable {
  static List<PlayerTemplate> players = [];

  static Future<void> load() async {
    final String jsonString = await rootBundle.loadString(
      'assets/data/players.json',
    );
    final List<dynamic> data = jsonDecode(jsonString);

    players = data.map((e) => PlayerTemplate.fromJson(e)).toList();
  }

  static PlayerTemplate? get(String id) {
    try {
      return players.firstWhere((player) => player.id == id);
    } catch (e) {
      return null;
    }
  }
}
