import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, FormControl, Validators } from '@angular/forms';
import { Notify } from 'src/app/models/notify.model';
import { SaleProduct } from 'src/app/models/sale-product.model';
import { MessageService } from 'src/app/services/messages.service';
import { ShoppingService } from 'src/app/services/shopping.service';

@Component({
  selector: 'app-modal-notify-stock',
  templateUrl: './modal-notify-stock.component.html',
  styleUrls: ['./modal-notify-stock.component.scss']
})
export class ModalNotifyStockComponent implements OnInit {

  @Input() product: SaleProduct;
  user = JSON.parse(localStorage.getItem('user'));
  preCustomer = JSON.parse(localStorage.getItem('preCustomer'));

  constructor(
    private fb: FormBuilder,
    private shoppingService: ShoppingService,
    private mensagesService: MessageService) { }

  public formNotify = this.fb.group({
    nameSeller: new FormControl('', [Validators.required, ]),
    product: new FormControl('', [Validators.required, ]),
    brand: new FormControl('', [Validators.required, ]),
    document: new FormControl('', [Validators.required, ]),
    name: new FormControl('', [Validators.required, ]),
    cellPhone: new FormControl('', [Validators.required, ]),
    email: new FormControl('', [Validators.required, ]),
  });

  ngOnInit(): void {

    this.formNotify.patchValue({
      nameSeller: this.user.username,
      product: this.product.title,
      brand: this.product.brand,
    });
    if (this.preCustomer) {
      this.formNotify.patchValue({
        document: this.preCustomer.document ?? null,
        name: this.preCustomer.name ?? null,
        cellPhone: this.preCustomer.cellPhone ?? null,
      });
    }
  }


  createNotify() {
    const notify: Notify =
    {
      idSeller: this.user.seller,
      document: this.formNotify.get('document').value,
      name: this.formNotify.get('name').value,
      cellPhone: this.formNotify.get('cellPhone').value,
      email: this.formNotify.get('email').value,
      codprod: this.product.idProduct,
      notification: '',
    };

    this.shoppingService.createNotify(notify).subscribe(
      result => console.log(result),
      (err) => {
        switch (err.status) {
          case 404: {
            this.mensagesService.showInformation('Ops! Algo deu errado!', err.message);
            console.log('Pagina não encontrada');
            break;
          }
          default: {
            console.log(err);
            break;
          }
        }
      }
    );

  }

}
