import { Component, OnInit } from '@angular/core';
import { Supplier } from '../../model/supplier';
import { Item } from '../../model/item';
import { ApiCallService } from '../../service/apicall.service';
import { NgModel, NgForm } from '@angular/forms';
import { URLSearchParams } from '@angular/http';
import { Subject } from 'rxjs/Subject';
import { Observable } from 'rxjs/Observable';
// import { } from 'rxjs/Rx';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/do';
// test imports
import { EventEmitter, Input, Output, AfterViewInit } from '@angular/core';
import { AbstractControl, FormArray, FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';
// import { Resource } from '../../resources/resource';
@Component({
selector: 'app-supplier',
templateUrl: './supplier.component.html',
styleUrls: ['./supplier.component.css']
})
export class SupplierComponent implements OnInit, AfterViewInit {
suppliers: Observable<Supplier[]>;
supplier = {};
item = {};
private searchTerms = new Subject<any>();
supplierCount: number;
xRows: number = 5;
currentPage: number = 1;
loads: boolean = false;
params: URLSearchParams = new URLSearchParams();
pagesToShow: number = 10;
constructor(
private api: ApiCallService
) { }
public newItem(item: Item): void {
item.supplier = { id: item.supplier };
this.api.addItem(item).then(() => location.reload());
}
public newSupplier(supplier: Supplier): void {
this.api.addSupplier(supplier).then(() => location.reload());
}
ngOnInit(): void {
this.offsetLimit();
this.suppliers = this.searchTerms
.debounceTime(300)
.distinctUntilChanged()
.do(_ => this.loads = true)
.switchMap(
params => {
this.api.getCountSuppliers(this.params).then(n => this.supplierCount = n);
return this.api.suppliersSearch(this.params);
}
).do(_ => this.loads = false);
let n = 1000;
}
ngAfterViewInit(): void {
this.searchTerms.next(this.params.toString());
}
filter(param: any): void {
console.log(param);
this.params.set('phone', param.phone || "");
this.params.set('name', param.name || "");
this.searchTerms.next(this.params.toString());
}
offsetLimit(): void {
let offset = (this.currentPage * this.xRows) - this.xRows;
this.params.set('offset', offset + '');
this.params.set('limit', this.xRows + '');
}
prevPage(): void {
this.goToPage(this.currentPage - 1);
}
nextPage(): void {
this.goToPage(this.currentPage + 1);
}
goToPage(e): void {
this.currentPage = e;
this.offsetLimit();
this.searchTerms.next(this.params.toString());
}
private populateSuppliers(): void {
this.api.getCountSuppliers(this.params).then(n => this.supplierCount = n).then(_ => this.suppliers = this.api.suppliersSearch(this.params));
}
}