import { Component, OnInit } from '@angular/core';
import { ProductsService } from '../services/products.service';
import { Product } from '../models/product.model';
import { UxService } from '@eui/core';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';

@Component({
    templateUrl: './products.component.html',
    styleUrls: ['./products.component.scss'],
})
export class ProductsComponent implements OnInit {
    formInput: FormGroup;
    product: Product;
    products: Array<Product>;
    actionLabel: string;
    serviceError: null;
    IdSelected: number;
    ItemSelected: Product;
    mode = null;
    modes: string [] = [];


    constructor(protected productsService: ProductsService, public uxService: UxService, private fb: FormBuilder) {

    }

    ngOnInit() {
        this.loadProducts();
        this.buildForm();

    }

    loadProducts() {
        this.serviceError = null;
        this.productsService.loadProducts().subscribe(products => {
            this.products = products.items;
        }, error => {
            this.serviceError = error;
        });
    }

    buildForm(): void {

        this.formInput = this.fb.group({
            'name': [null , [Validators.required]],
            'price': [null , [Validators.required]],
            'description': [null , [Validators.required]]
        });
    }

    editProduct(item: Product) {
        this.ItemSelected = item;
        this.actionLabel = 'Edit product';
        this.uxService.openModal('modal1b');
    }

    deleteProduct(id: number) {
        this.IdSelected = id;
        this.uxService.openModal('modaldelete');
    }

    onModalAccept(event) {
        this.productsService.deleteProduct(this.IdSelected).subscribe(product => {
            let index = this.products.findIndex(item => item['productId'] === product['productId']);
            this.products.splice(index, 1);
        });
        this.uxService.closeModal('modaldelete');
    }

    onModalDismiss(event) {
        this.uxService.closeModal('modaldelete');
    }

    onModalClose(event) {
        this.uxService.closeModal('modaldelete');
    }

    addItem() {
        this.ItemSelected = null;
        this.actionLabel = 'New product';
        this.formInput.reset();
        this.uxService.openModal('modal1b');
    }

    onSubmit() {
        this.product = new Product(this.formInput.value);
        this.productsService.addProduct(this.product).subscribe(product => {
            this.products.push(product);
            this.uxService.closeModal('modal1b');
        }, error => {
            this.serviceError = error;
        });
    }

    onUpdateSubmit(ItemSelected: Product) {
        this.product = new Product(this.formInput.value);
        this.productsService.updateProduct(ItemSelected).subscribe(product => {
            this.uxService.closeModal('modal1b');
        }, error => {
            this.serviceError = error;
        });
    }

}
