import { Component, Input, OnInit } from '@angular/core';
import { MD2Icon, TreasureType } from '../massive-darkness2.model';
import { MD2Service } from '../../../services/MD2/md2.service';

@Component({
  selector: 'md2-icon',
  templateUrl: './md2-icon.component.html',
  styleUrls: ['./md2-icon.component.scss']
})
export class MD2IconComponent implements OnInit {

  @Input() iconClass: string = 'mr-1';
  isImageIcon: boolean = false;
  imgUrl: string;
  iconHtml: string;
  private _icon: string | MD2Icon;

  @Input() public set icon(v: string | MD2Icon) {
    if (v !== undefined) {
      if (this._icon != v) {
        this._icon = v;
        //if it's string, convert it to MD2Icon
        if (typeof v === 'string') {
          const key = Object.keys(MD2Icon).find(
            k => k.toLowerCase() === v.toString().toLowerCase()
          );
          if (key) {
            v = MD2Icon[key as keyof typeof MD2Icon];
          }
        }
        this.initIcon(v as MD2Icon);
      }
      if (this.isMD2Icon(v)) {
        this.iconName = MD2Icon[v].toLowerCase();
      } else {
        this.iconName = v;
      }
    }

  }

  isMD2Icon(icon: MD2Icon | string): icon is MD2Icon {
    return Number.isInteger(icon);
  }
  @Input() size: string = 'sm';
  iconName: string;
  constructor(private md2Service: MD2Service) { }

  ngOnInit(): void {
  }

  private initIcon(icon: MD2Icon): void {
    if (icon < MD2Icon.TreasureToken) {
      this.isImageIcon = false;
      this.iconHtml = this.md2Service.iconHtml(icon);
    } else {
      this.isImageIcon = true;
      this.imgUrl = this.md2Service.iconHtml(icon);

    }
  }

  public get sizeClass(): string {
    switch (this.size) {
      case 'sm':
        return this.isImageIcon ? 'g-width-25 img-fluid' : 'g-font-size-18'
        break;
      case 'med':
        return this.isImageIcon ? 'g-width-35 img-fluid' : 'g-font-size-30'
        break;
      case 'lg':
        return this.isImageIcon ? 'g-width-50 img-fluid' : 'g-font-size-50'
        break;

      default:
        return this.isImageIcon ? 'g-width-20 img-fluid' : 'g-font-size-' + this.size;
        break;
    }
  }

}
