from ..objects.pokemon import Pokemon from ..core.location import Location from thefuzz.fuzz import partial_ratio from sqlalchemy.orm import Session from sqlalchemy.engine import Engine from typing import List from sqlalchemy import desc from datetime import datetime, timedelta class PokemonList(): def __init__(self, engine: Engine): self.pokemons = None self.engine = engine self.timedelta = timedelta(minutes=2) def sort_by_name(self, reverse=False): with Session(self.engine) as session: if reverse: result = session.query(Pokemon).where(Pokemon.end_time > datetime.now() + self.timedelta)\ .order_by(desc(Pokemon.name)) else: result = session.query(Pokemon).where(Pokemon.end_time > datetime.now() + self.timedelta)\ .order_by(Pokemon.name) session.commit() return result.all() def sort_by_cp(self, reverse=False): self.pokemons.sort(key=lambda pokemon: pokemon.cp, reverse=reverse) def sort_by_level(self, reverse=False): self.pokemons.sort(key=lambda pokemon: pokemon.level, reverse=reverse) def sort_by_distance(self, location: Location, reverse=False): self.pokemons.sort(key=lambda pokemon: location.distance(pokemon.location), reverse=False) def get_at(self, index:int): return self.pokemons[index] def search_by_name(self, query:str): return PokemonList(*filter(lambda pokemon: partial_ratio(query.lower(), pokemon.name) >= 80, self.pokemons)) def insert_to_database(self, pokemons: List[Pokemon]): with Session(self.engine) as session: session.add_all(pokemons) session.commit()