import { Component, OnInit, Input } from '@angular/core';
import { NbToastrService, NbDialogRef } from '@nebular/theme';
import { Item, Character, SRToken, Signup } from '../../../../../../backend/Types/Types';
import { getClassColor } from '../../../../../../backend/Types/PlayerSpecs';
import { _Tiers, Tiers } from '../../../../../../backend/Types/Items';
import { IApiService } from '../../services/ApiService/ApiService';

@Component({
    selector: 'buyToken',
    template: `
    <nb-card style="width: 500px">
      <nb-card-header>
        Buy {{item.itemname}}
      </nb-card-header>
      <nb-card-body>
        <p>
          You have {{currency}} softreserve(s) remaining
        </p>  
        <div *ngIf="currency>0">
            <nb-alert accent="danger" *ngIf="invalidatedTokens.length > 0">
                Claiming this reserve puts the following streaks to zero <br />
                <span>
                  <nb-icon icon="alert-triangle-outline" status="warning"></nb-icon>&nbsp;This is not reversible&nbsp;<nb-icon icon="alert-triangle-outline" status="warning"></nb-icon>
                </span>
                <ul *ngFor="let item of invalidatedTokens">
                    <li>
                        [ {{item.level}} ] 
                        <img style="min-width: 20px; width: 2.25vw; max-width: 35px" [src]="'https://wow.zamimg.com/images/wow/icons/large/'+item.iconname+'.jpg'" />
                        <span [ngStyle]="{'color':item.quality=='Epic'?'#a335ee':'#ff8000'}">
                            {{item.itemname}}
                        </span>
                    </li>
                </ul>
            </nb-alert>
            
            <nb-alert accent="info" *ngIf="noToken">  
                The following reserve will be created<br />
                <ul>
                    <li>
                        [ {{1+currency+modifier}} ] 
                        <img style="min-width: 20px; width: 2.25vw; max-width: 35px" [src]="'https://wow.zamimg.com/images/wow/icons/large/'+item.iconname+'.jpg'" />
                        <span [ngStyle]="{'color':item.quality=='Epic'?'#a335ee':'#ff8000'}">
                        {{item.itemname}}
                        </span>
                        <span *ngIf="modifier>0">(<b>+{{modifier}}</b> from priorities)</span>
                    </li>
                </ul>
              
            </nb-alert>

            <nb-alert accent="info" *ngIf="upgradableToken != null">
                The following reserve will be upgraded<br />
                <ul>
                    <li>
                        [ {{upgradableToken.level}} ] => [ {{upgradableToken.level+1+currency}} ] <img style="min-width: 20px; width: 2.25vw; max-width: 35px" [src]="'https://wow.zamimg.com/images/wow/icons/large/'+upgradableToken.iconname+'.jpg'" />
                        <span [ngStyle]="{'color':upgradableToken.quality=='Epic'?'#a335ee':'#ff8000'}">{{upgradableToken.itemname}}</span>
                    </li>
                </ul>
              </nb-alert>
            </div>
            <button
                  (click)="buyToken()"
                  [disabled]="currency<=0"
                  nbButton 
                  outline 
                  status="success" 
                  size="small">
                  <nb-icon icon="checkmark-outline"></nb-icon> okay
            </button>
      </nb-card-body>
  </nb-card>
    
    `,
  })
  export class FrontcraftBuyTokenComponent implements OnInit{
    @Input() characterName: string
    @Input() item : Item
    @Input() signup : Signup
    @Input() tier: Tiers

    invalidatedTokens: (SRToken & Character & Item)[] | undefined = []
    upgradableToken : (SRToken & Character & Item) | undefined
    noToken = false
    modifier
    currency: number = 0
  
    constructor(
      private toastr: NbToastrService,
      protected dialogRef: NbDialogRef<FrontcraftBuyTokenComponent>,
      private api : IApiService
    ){}
  
    async ngOnInit() {
        const char = await this.api.get('CharacterManager').getCharacterByName(this.characterName)
        if(!char) return

        const passiveStreaks = await this.api.get('ItemManager').getTokens(char, [this.item.tier], false)
        this.upgradableToken = passiveStreaks.find(p => p.itemname === this.item.itemname)
        this.invalidatedTokens = passiveStreaks.filter(token => token.itemname !== this.item.itemname)
        if(!this.upgradableToken)                
            this.upgradableToken = await this.api.get('ItemManager').getToken(char, this.item, true)                
        this.modifier = await this.api.get('ItemManager').calculatePriorities(this.item.itemname, char)

        if(!this.upgradableToken) this.noToken = true

        const usr = this.api.getCurrentUser()
        this.api.get('CharacterManager')
        .getCharactersOfUser(usr.username)
        .then(chars => {
            chars.forEach(async char => {
                char['color'] = getClassColor(char.class)
            })
        })
        this.api.get('UserManager').getUser(usr.username).then(u => {
          if(!u) return
          this.currency = u[this.tier] || 0
        })
    }
  
    buyToken = async () => {
        const src = this.api.get('ItemManager')
        const token = await src.buyToken(this.api.getAuth().token.value, this.characterName, this.item.itemname, this.signup)
    
        if(token){
        this.toastr.show(token.charactername+' now has a token for '+token.itemname+' of level '+token.level, 'Yay', {status: 'success'})
        }else{
        this.toastr.show('Error (something went wrong)', 'Oh no', {status: 'danger'})
        }
        this.dialogRef.close()
    }
  }