import { Component, Input, OnChanges, OnDestroy, OnInit, SimpleChanges } from "@angular/core";
import { styleChangedObserver } from "src/app/components/header/header.component";
import { EnvironmentService } from "src/environments/environment.service";
import { AccountAvatarRecord, MeRecord } from "../../server-services/query-records/account-records";
@Component({
  selector: "app-avatar",
  templateUrl: "./avatar.component.html",
  styleUrls: ["./avatar.component.scss"],
})
export class AvatarComponent implements OnInit, OnChanges, OnDestroy {
  @Input() img?: string;
  @Input() accountAvatarRecord?: AccountAvatarRecord;
  @Input() blob?: ArrayBuffer;
  public src: string = "";

  constructor(private environmentService: EnvironmentService) {
    styleChangedObserver.subscribe(() => this.ngOnChanges())
  }
  
  ngOnChanges(): void {
    if (this.accountAvatarRecord?.avatarImageKey) {
      this.src = this.environmentService.url_api + "/r/avatar/" + this.accountAvatarRecord.id + "/" + this.accountAvatarRecord.avatarImageKey;
    } else if (this.img) {
      this.src = this.img;
    } else if (this.blob) {
      var urlCreator = window.URL || window.webkitURL;
      this.src = urlCreator.createObjectURL(new Blob([this.blob]));
    }
    else{
      this.setDefaultImage();
    }
  }

  setDefaultImage(){
    var styleMode = localStorage.getItem("style_mode");
    if(this.accountAvatarRecord)
      this.src = this.environmentService.site_base + `/assets/img/ui/user-${styleMode}.svg`;
    else
      this.src = this.environmentService.site_base + `/assets/img/ui/room-${styleMode}.svg`;
  }

  ngOnInit(): void {}

  ngOnDestroy(): void {
    var urlCreator = window.URL || window.webkitURL;
    urlCreator.revokeObjectURL(this.src);
  }
}
