import { ChangeDetectorRef, Component, inject, OnInit } from '@angular/core'; import { ChainFormGroup } from '../chain-formgroup'; import { ChainForm } from '../chain-form/chain-form'; import { ActivatedRoute } from '@angular/router'; import { Observable, take, tap } from 'rxjs'; import { Chain } from '../../../../models/Chain'; import { ImageStorage } from '../../../../services/image-storage'; import { ActionBtn } from '../../../../components/action-btn/action-btn'; import { TranslatePipe } from '@ngx-translate/core'; import { UpperfirstPipe } from '../../../../pipes/upperfirst-pipe'; import { ChainSettings } from '../../../../services/chain-settings'; @Component({ selector: 'app-chain-edit', imports: [ChainForm, ActionBtn, TranslatePipe, UpperfirstPipe], templateUrl: './chain-edit.html', styleUrl: './chain-edit.scss', }) export class ChainEdit implements OnInit { readonly form = new ChainFormGroup(); protected readonly activatedRoute = inject(ActivatedRoute); private readonly cd = inject(ChangeDetectorRef); private chain?: Chain; private readonly imageStorage = inject(ImageStorage); private readonly chainSettings = inject(ChainSettings); ngOnInit() { (>this.activatedRoute.data) .pipe( take(1), tap((data) => (this.chain = new Chain(data.chain.name, data.chain.image, data.chain.id))), tap(async (data) => await this.patchForm(data.chain)), ) .subscribe(); } get disabled() { return this.form.invalid || this.form.pristine; } async patchForm(chain: Chain) { try { this.form.controls.name.patchValue(chain.name); if (chain.image) { const imgName = chain.image; const blob = await this.imageStorage.getImage(imgName); const file = new File([blob], imgName, { type: blob.type }); this.form.controls.image.patchValue(file); this.cd.detectChanges(); } } catch (e) { console.error(e); //TODO: reportar error } } async update() { if (this.chain) { const updatedName = this.form.controls.name.value; const updatedImg = this.form.controls.image.value; const updatedChain = new Chain(updatedName, '', this.chain.id); await this.chainSettings.update(this.chain, updatedChain, updatedImg); } } }