import { Injectable } from '@angular/core';
import {
  AngularFirestore,
  AngularFirestoreCollection
} from '@angular/fire/firestore';
import { take } from 'rxjs/operators';
import { ContactData } from './services/contact';
import { ServiceService } from './service.service';
import { Router, ActivatedRoute } from '@angular/router';

@Injectable({
  providedIn: 'root'
})
export class ContactService {
  loader: boolean;
  constructor(
    public afs: AngularFirestore,
    private router: Router,
    private service: ServiceService
  ) {
    this.loader = false;
  }

  contactCreate(data: ContactData) {
    this.loader = true;
    this.afs
      .collection('contacts')
      .add({})
      .then(docRef => {
        data.contactId = docRef.id;
        this.afs
          .collection('contacts')
          .doc(data.contactId)
          .set(data)
          .then(() => {
            this.service
              .showToast('Thank you for your feedback!', 'top', 'my-toast', 500)
              .then(() => {
                this.loader = false;
                console.log('redirected');
                setTimeout(() => {
                  this.router.navigateByUrl('home');
                }, 500);
              })
              .catch(err => {
                this.loader = false;
              });
          });
      });
  }
}
