import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { DataBindingDirective } from '@progress/kendo-angular-grid';
import { Observable, of, Subscription } from 'rxjs';
import { catchError, tap } from 'rxjs/operators';
import { CategoryPartner } from 'src/app/models/category-partner.model';
import { PartnerCategory } from 'src/app/models/partner-category.model';
import { PartnerCategoryService } from 'src/app/services/partner-category.service';

@Component({
  selector: 'app-parnter-category-home',
  templateUrl: './parnter-category-home.component.html',
  styleUrls: ['./parnter-category-home.component.scss']
})
export class ParnterCategoryHomeComponent implements OnInit, OnDestroy {
  @ViewChild(DataBindingDirective) dataBinding: DataBindingDirective;
  public gridView: unknown[];
  formFilter: FormGroup;
  formPartner: FormGroup;
  partnerCategory$: Observable<PartnerCategory[]>;
  partnerCategories: PartnerCategory[] = [];
  subscriptionCategory: Subscription;
  isloading = false;

  public opened = false;


  constructor(
    private readonly partnerCategoryService: PartnerCategoryService,
    private route: ActivatedRoute,
    private router: Router
  ) {
    this.formFilter = new FormGroup({
      description: new FormControl(null),
      type: new FormControl(null),
    });
    this.formPartner = new FormGroup({
      id: new FormControl(),
      name: new FormControl('', [Validators.required, Validators.minLength(10)]),
      partnerType: new FormControl('', [Validators.required]),
      paymentType: new FormControl('', [Validators.required]),
      descriptionType: new FormControl(''),
      descriptionPayment: new FormControl('')
    });
  }

  ngOnInit(): void {
  }

  ngOnDestroy(): void {
    if ( this.subscriptionCategory ) {
      this.subscriptionCategory.unsubscribe();
    }
  }

  getPartnerCategory()  {
    const description = this.formFilter.get('description').value;
    const type = this.formFilter.get('type').value;

    this.partnerCategory$ = this.partnerCategoryService.getPartnerCategory(description, type);
    this.subscriptionCategory = this.partnerCategory$.subscribe(partnerCategory => {
      this.partnerCategories = partnerCategory;
      this.gridView = this.partnerCategories;
    });
  }

  editPartner(data) {
    console.log(data);
    this.router.navigate([`/partner/category/edit/category/${data.dataItem.id}`]);
  }

  createPartnerCategory() {
    this.router.navigate([`/partner/category/create/category`]);
  }

  public submitForm(): void {
    this.formPartner.markAllAsTouched();
    console.log(this.formPartner.valid);
    console.log(this.formPartner.errors);
    //    if (this.formPartner.valid) {
    const data = JSON.stringify(this.formPartner.value);
    const partnerCategory: PartnerCategory = JSON.parse(data);

    console.log(JSON.stringify(partnerCategory));
    this.partnerCategoryService.createOrReplace(this.formPartner.value).pipe(
      tap((resultData: PartnerCategory) => {
        this.isloading = false;
        // TODO: INCLUIR MENSAGEM
        this.opened = false;
        const categoryBD = this.partnerCategories.find(p => p.id === resultData.id);
        console.log('CategoryBD: ' + JSON.stringify(categoryBD));
        const index = this.partnerCategories.indexOf(categoryBD);
        console.log('Index ' + index);

        const categoryData = new PartnerCategory();
        categoryData.id = resultData.id;
        categoryData.name = resultData.name;
        categoryData.partnerType = resultData.partnerType;
        categoryData.paymentType = resultData.paymentType;
        categoryData.descriptionType = ( resultData.partnerType === 'P') ? 'PARCEIRO' :
                            ( resultData.partnerType === 'B') ? 'BELLA OBRA' : 'MESTRE JURUNENSE';
        categoryData.descriptionPayment = (resultData.paymentType === 'C') ? 'Crédito' : 'Contas a Pagar';


        if ( index === -1) {
          this.partnerCategories.push(categoryData);
        } else {
          this.partnerCategories[index] = categoryData;
        }
      }),
      catchError((error) => {
        this.isloading = false;
        // TODO: INCLUIR MENSAGEM
        console.log(error);
        return of(error);
      })
    ).subscribe();

    console.log(JSON.stringify(this.formPartner.value));
  }

  public clearForm(): void {
    this.formPartner.reset();
    this.opened = false;
  }


  populatePartnerCategory(data: PartnerCategory) {
    this.formPartner.patchValue({
      id: data.id,
      name: data.name,
      partnerType: data.partnerType,
      paymentType: data.paymentType,
      descriptionType: data.descriptionType,
      descriptionPayment: data.descriptionPayment,
    });
  }


  public close(): void {
    this.opened = false;
  }

  public open(data: any): void {
    this.formPartner.reset();
    if ( data != null) {
      const categoryPartner = data.dataItem as PartnerCategory;
      this.populatePartnerCategory(categoryPartner);
    }
    this.opened = true;
  }


}
