import { Component, OnInit,  ViewChild, AfterViewInit } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { Router, ActivatedRoute } from '@angular/router';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';
import { MatSort } from '@angular/material/sort';
import  { LotDetailDialogComponent } from './lot-detail-dialog/lot-detail-dialog.component';

import * as moment from 'moment';

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

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

@Component({
  selector: 'app-favorites-page',
  templateUrl: './sale-detail-page.component.html',
  styleUrls: ['./sale-detail-page.component.css']
})


export class SaleDetailPageComponent implements OnInit, AfterViewInit {
  
  id: any = '';  
  Sale: Sale;  

  displayedColumns: string[] = ['lotNum', 'picture', 'title', 'estimateLow', 'estimateHigh', 'price', 'nbrBids', 'duration', 'percentageAboveUnderLow', 'percentageAboveUnderHigh'];  
  lotList: MatTableDataSource<Lot> = new MatTableDataSource<Lot>();
  @ViewChild(MatPaginator) paginator?: MatPaginator;
  @ViewChild(MatSort) sort?: MatSort;

  constructor(
    private route: ActivatedRoute,
    private notificationService: NotificationService,
    private router: Router,
    public dialog: MatDialog,
    private apiSaleService: apiSaleService,
    private apiLotService: apiLotService) {

      this.Sale = {
        _id: { $oid: '' },
        idPlatform: '',
        platform: '',
        url: '',
        title: '',
        date: '',
        location: '',
        saleHouseName: '',
        status: '',
        postProcessing: {
          nbrLots: 0,
          duration: 0,
          bidsDuration: 0,
          durationPerLots: '',
          totalAmount: 0,
          averageAmount: '',
          medianAmount: '',
          minAmount: '',
          maxAmount: '',
          unsoldLots: 0,
          unsoldPercentage: ''
        }
      }

    }

  ngOnInit(): void {
    this.route.paramMap.subscribe(params => {      
      this.id = params.get('id');
      
      this.getSale(); 
      this.getLotList();
    });
  }

  ngAfterViewInit(): void {
    
  }

  getSale(){
    this.apiSaleService.getSale(this.id).subscribe((sale: Sale) => {      
      this.Sale = sale;      
    });
  }

  getLotList(){
    this.apiLotService.getLotsBySale(this.id).subscribe((lotList: Lot[]) => {

      // adding the Bids length info
      lotList = lotList.map((lot) => {
        return {...lot, bidsLength: lot.postProcessing ? lot.postProcessing.nbrBids : 0};
      });

      // adding the picture info
      let path = '';
      lotList = lotList.map((lot) => {
        switch (lot.platform) {
          case 'drouot':
            path = 'https://cdn.drouot.com/d/image/lot?size=phare&path='+(lot.RawData as { photos?: { path: string }[] })?.photos?.[0]?.path;
            return {...lot, picture: path ?? ''};

          case 'interencheres':
            path = (lot.RawData as { medias?: { lg: string }[] })?.medias?.[0]?.lg ?? '';
            return {...lot, picture: path};

          default:
            return {...lot, picture: ''};
        }
      });

      // adding the duration info
      lotList = lotList.map((lot) => {
        return {...lot, duration: lot.postProcessing ? lot.postProcessing.duration : 0};
      });
      
      // adding the percentageAboveUnderLow info
      lotList = lotList.map((lot) => {
        return {...lot, percentageAboveUnderLow: lot.postProcessing ? lot.postProcessing.percentageAboveUnderLow : 0};
      });

      // adding the percentageAboveUnderHigh info
      lotList = lotList.map((lot) => {
        return {...lot, percentageAboveUnderHigh: lot.postProcessing ? lot.postProcessing.percentageAboveUnderHigh : 0};
      });

      // adding the Auctionned ammount info
      lotList = lotList.map((lot) => {
        return {...lot, auctionedAmount: lot.auctioned?.amount ? lot.auctioned?.amount : 0};
      });

      console.log(lotList);
      this.lotList = new MatTableDataSource(lotList);      
      this.lotList.paginator = this.paginator ?? null;
      this.lotList.sort = this.sort ?? null;
    });
  }

  // getDurationInMinutes(duration: number): number {
  //   return Math.floor(duration / 60);
  // }

  getTimePerLot(duration: number): string {

    const minutes = Math.floor((duration % 3600) / 60);
    const seconds = duration % 60;

    let returnString = '';

    if (minutes > 0) {
      returnString += minutes + 'm ';
    }
    returnString += seconds + 's';

    return returnString;
  }

  parseToNumber(value: string | null): number {
    return parseFloat(value || '0');
  }

  convertSecondsToHHMM(seconds: number): string {
    const h = Math.floor(seconds / 3600);
    const m = Math.floor((seconds % 3600) / 60);
    return `${h.toString().padStart(2, '0')}:${m.toString().padStart(2, '0')}`;
  }

  openDetailLot(idLot: string): void {
    this.dialog.open(LotDetailDialogComponent, {
      width: '80%',
      data: {id: idLot}
    });
  }

  downloadExcelStatsFile(_id: String): void {
    this.apiSaleService.getSaleStatXsl(_id).subscribe((data: Blob) => {
        const downloadURL = window.URL.createObjectURL(data);
        const link = document.createElement('a');
        link.href = downloadURL;
        link.download = 'SaleStats.xlsx';
        link.click();
    });
}




}

