import { Component, OnInit, OnDestroy } from '@angular/core';
import { Title } from '@angular/platform-browser';
import { MatDialog } from '@angular/material/dialog';
import { Router } from '@angular/router';
import { LoadingSaleDialogComponent } from './loading-sale-dialog/loading-sale-dialog.component';
import * as moment from 'moment';

// Services
import { NotificationService } from 'src/app/core/services/notification.service';
import { apiSaleService } from 'src/app/core/services/api/api.sale.service';

import { Sale } from 'src/app/core/services/model/sale.interface';

@Component({
  selector: 'app-favorites-page',
  templateUrl: './sales-page.component.html',
  styleUrls: ['./sales-page.component.css']
})
export class SalesPageComponent implements OnInit,OnDestroy {
  
  url: string = '';
  refreshSalesId: any;
  displayedColumns: string[] = ['title', 'date', 'house', 'plateform', 'status', 'action'];
  displayedColumnsOld: string[] = ['title', 'date', 'house', 'plateform', 'status', 'postProcessing', 'delete'];

  futureSales = []
  pastSales = []

  constructor(
    private notificationService: NotificationService,
    private router: Router,
    public dialog: MatDialog,
    private apiSaleService: apiSaleService,
    private titleService: Title) {}

  openLoadingSale(): void {
      const dialogRef = this.dialog.open(LoadingSaleDialogComponent, {
        width: '300px',
        data: {url: this.url}
      });
    
      dialogRef.afterClosed().subscribe(result => {
        if (result) {
          this.refreshSales();
          this.url = "";
          this.notificationService.openSnackBar("Sale Added");
        }
      });
  }

  refreshSales(): void {
    this.apiSaleService.getAllSale().subscribe((data: any) => {
      console.log(data);
      const today = moment().startOf('day');

      this.futureSales = data
          .filter((element: Sale) => moment(element.date).isAfter(today))
          .sort((a: any, b: any) => moment(a.date).isAfter(b.date) ? 1 : -1);

      this.pastSales = data
          .filter((element: Sale) => moment(element.date).isBefore(today))
          .sort((a: any, b: any) => moment(a.date).isAfter(b.date) ? 1 : -1);
    });
  }

  trackByElementId(index: number, element: any): string {
    return element._id;
  }
    
  ngOnInit(): void {
    this.titleService.setTitle('Jucundus - Sales');
    this.refreshSales();
    this.refreshSalesId = setInterval(() => {
      this.refreshSales();
    }, 5000);    
  }
  ngOnDestroy() {
    if (this.refreshSalesId) {
      clearInterval(this.refreshSalesId);
    }
  }

  prepareSale(Sale: Sale): void {
    
    this.apiSaleService.prepareSale(Sale).subscribe( data => {
      console.log(data);
      this.refreshSales();
      this.notificationService.openSnackBar("Prepare Sale");

    })
  }

  followSale(Sale: Sale): void {
    
    this.apiSaleService.followSale(Sale).subscribe( data => {
      console.log(data);
      this.refreshSales();
      this.notificationService.openSnackBar("Sale followed");

    })
  }

  stopFollowSale(Sale: Sale): void {
    Sale.status = "askStop";
    this.apiSaleService.updateSale(Sale).subscribe( data => {
      this.refreshSales();    
      this.notificationService.openSnackBar("Sale Stopping...");
    })
  }

  deleteSale(_id: string): void {
    this.apiSaleService.deleteSale(_id).subscribe( data => {
      this.refreshSales();    
      this.notificationService.openSnackBar("Sale deleted");
    })
  }

  resetToReady(_id: string): void {
    this.apiSaleService.resetSaleToReady(_id)
  }

  navigateToSaleDetail(id: string) {
    console.log(id);
    clearInterval(this.refreshSalesId);
    this.router.navigate(['/sales/detail', id]);
  }

  postProcessing(id: string) {
    this.apiSaleService.postProcessing(id).subscribe( data => {      
      this.notificationService.openSnackBar("Sale processing");
    })
  }

}

