import { Injectable } from '@angular/core';
import {
  AngularFirestore,
  AngularFirestoreCollection
} from '@angular/fire/firestore';
import { Search } from './services/search';
import { database } from 'firebase';
import { take } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class SearchService {
  searchList: Search[] = [];
  constructor(public afs: AngularFirestore) {}

  public async search(inputText: string) {
    if (inputText === '') {
      this.searchList = [];
      return;
    }
    const This = this;
    const state = true;
    this.searchList = [];
    // tslint:disable-next-line:max-line-length
    const orderRef: AngularFirestoreCollection<any> = this.afs.collection(
      'shoppers',
      ref =>
        ref
          .where('status', '==', state)
          .orderBy('name')
          .startAt(inputText.toUpperCase())
          .endAt(inputText.toLowerCase() + '\uf8ff')
          .limit(5)
    );
    orderRef.valueChanges().subscribe(value => {
      const res = value;
      if (res.length > 0) {
        res.forEach(item => {
          // console.log(item);
          const shopper: Search = {
            text: item.name,
            data: item,
            type: 'shopper'
          };
          this.searchList.push(shopper);
        });
      }
    });

    // tslint:disable-next-line:max-line-length
    const prodRef: AngularFirestoreCollection<any> = this.afs.collection(
      'products',
      ref =>
        ref
          .where('status', '==', state)
          .orderBy('prodName')
          .startAt(inputText.toUpperCase())
          .endAt(inputText.toLowerCase() + '\uf8ff')
          .limit(5)
    );
    prodRef.valueChanges().subscribe(values => {
      const result = values;
      if (result.length > 0) {
        result.forEach(item => {
          console.log(item);
          const prod: Search = {
            text: item.prodName,
            data: item,
            type: 'product'
          };
          this.searchList.push(prod);
        });
        console.log(this.searchList);
      }
    });

    // tslint:disable-next-line:max-line-length
    const feaRef: AngularFirestoreCollection<any> = this.afs.collection(
      'category',
      ref =>
        ref
          .where('status', '==', state)
          .orderBy('catName')
          .startAt(inputText.toUpperCase())
          .endAt(inputText.toLowerCase() + '\uf8ff')
          .limit(5)
    );
    feaRef.valueChanges().subscribe(values => {
      const result = values;
      if (result.length > 0) {
        result.forEach(item => {
          console.log(item);
          const prod: Search = {
            text: item.catName,
            data: item,
            type: 'category'
          };
          this.searchList.push(prod);
        });
        console.log(this.searchList);
      }
    });
  }
}
