/**
 * class providing the actor and token, and choosing the name and image from the token if available.
 */
export class TokenActor {
  static fromTokenActor(token, actor){
    return token ? TokenActor.fromToken(token) : TokenActor.fromActor(actor)
  }

  static fromActorId(actorId, onError = () => undefined) {
    const controlled = canvas?.tokens?.controlled
    actorId = actorId ?? (controlled?.length > 0
      ? controlled[0]?.actor?.id
      : undefined)
    const actor = actorId ? game.actors.get(actorId) : undefined
    if (actor) {
      return this.fromActor(actor)
    }
    return onError()
  }

  static fromActor(actor) {
    const token = actor.isToken ? actor.token : actor.prototypeToken
    return TokenActor.fromToken(token)
  }

  static fromTokenId(tokenId, sceneId = undefined) {
    const tokensList = sceneId ? game.scenes.get(sceneId)?.tokens : canvas?.tokens?.placeables
    const token = tokensList.get(tokenId)
    return TokenActor.fromToken(token)
  }

  static fromToken(token) {
    return new TokenActor(token)
  }

  constructor(token) {
    this.name = token.name ?? token.actor.name
    this.img = token.actor.isToken && token.texture.src ? token.texture.src : token.actor.img
    this.actor = token.actor
    this.id = token.actor?.id
    this.token = token
    this.tokenId = token?.id
  }
}