import { Component, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { Observable } from 'rxjs';
import { AuthService } from 'src/app/auth/services/auth.service';
import { SaleProduct } from 'src/app/models/sale-product.model';
import { ProductService } from 'src/app/services/product.service';
import { AddItemAction, LoadShoppingItemsAction } from '../store/actions/shopping.action';
import { SaleState } from '../store/models/sale-state.model';
import { ShoppingItem } from '../store/models/shopping-item';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  pageNumber = 1;
  pageSize = 50;

  public windowTop = 100;
  public windowLeft = 0;
  public opened = false;

  products$: Observable<SaleProduct[]>;
  promotions$: Observable<SaleProduct[]>;
  shopping$: Observable<ShoppingItem[]>;
  images: string[] = [];

  loading$: Observable<boolean>;
  error$: Observable<Error>;
  newShoppingItem: ShoppingItem = {
    id: null, invoiceStore: null, idCart: null, idProduct: null, description: null,
    image: null, productType: null, quantity: null, price: null, promotion: null,
    deliveryType: null, stockStore: null, seller: null, listPrice: null,
    discount: null, discountValue: null, userDiscount: null, mutiple: null,
    auxDescription: null, smallDescription: null, brand: null, ean: null,
    percentUpQuantity: null, upQuantity: null, base: null, line: null,
    can: null, color: null, letter: null,
  };

  constructor(private productService: ProductService,
              private store: Store<SaleState>,
              private authService: AuthService
  ) {
  }

  ngOnInit(): void {


    this.shopping$ = this.store.select(store => store.shopping.list);
    this.loading$ = this.store.select(store => store.shopping.loading);
    this.error$ = this.store.select(store => store.shopping.error);

    this.store.dispatch(new LoadShoppingItemsAction('906488c9-249f-4253-b5e7-25033d597229'));

    this.getSaleProducts();

    this.getSalePromotions();

  }

  public openClose(isOpened: boolean) {
    this.opened = isOpened;
  }

  getSaleProducts() {
    try {
      this.products$ = this.productService.getSaleProducts(this.authService.getStore(), this.pageNumber, this.pageSize);
    } catch (e) {
      console.log('Erro ao consultar produtos.');
      console.log(e);
    }
  }

  getSalePromotions() {
    try {
      this.promotions$ = this.productService.getSalePromotions(this.authService.getStore(), this.pageNumber, this.pageSize);
    } catch (e) {
      console.log('Erro ao consultar produtos.');
      console.log(e);
    }
  }


  getImage(urlImage: string) {
    if (urlImage === null) {
      return '';
    }
    if (urlImage.length > 0) {
      const re = /\s*;\s*/;
      if (urlImage.indexOf(';') === -1) {
        urlImage += ';';
      }
      this.images = urlImage.split(re);
      return this.images[0];
    }

  }

  addItem(value: SaleProduct) {
    try {
      console.log(value);
      this.store.dispatch(new AddItemAction({
        id: null, idCart: localStorage.getItem('idCart'), invoiceStore: this.authService.getStore(),
        idProduct: value.idProduct, description: value.title, image: this.getImage(value.urlImage), productType: value.productType,
        quantity: 1, price: value.salePrice, deliveryType: null, stockStore: null, seller: null, listPrice: value.listPrice,
        userDiscount: null, discount: null, discountValue: null, mutiple: null, ean: value.ean, percentUpQuantity: 0, upQuantity: 0,
        auxDescription: null, smallDescription: value.smallDescription, brand: value.brand, promotion: value.promotion,
        base: value.base, line: value.line, can: value.can, color: value.color, letter: value.letter
      }));
    } catch (e) {
      console.log(e);
    }
  }

}

