import { inject, Injectable } from '@angular/core'; import { Location } from '@angular/common'; import { Router } from '@angular/router'; import { ImageStorage } from './image-storage'; import { ProductDAO } from '../dao/ProductDAO'; import { Product } from '../models/Product'; @Injectable({ providedIn: 'root', }) export class ProductSettings { private readonly imageStorage = inject(ImageStorage); private readonly location = inject(Location); private readonly productDAO = inject(ProductDAO); private readonly router = inject(Router); async save(product: Product, img: File | null) { try { if (img) { const imgFileName = await this.imageStorage.saveImage(img); product.image = imgFileName; } await this.productDAO.insert(product); } catch (e) { //catch by message starts with SQLITE_CONSTRAINT_UNIQUE is duplicate console.error(e) //TODO: report problem } this.router.navigate(['settings', 'products']); this.location.replaceState('products'); } async update(prevProd: Product, updatedProd: Product, img: File | null) { try { let imgName = prevProd.name; if (img) { if (img.name !== imgName) { imgName = await this.imageStorage.saveImage(img); if (prevProd.image) { this.imageStorage.deleteImage(prevProd.image); } updatedProd.image = imgName; } } await this.productDAO.update(updatedProd, { id: updatedProd.id }); } catch (e) { console.error(e); //TODO: report problem } this.router.navigate(['settings', 'products']); this.location.replaceState('products'); } }