import { Component, OnInit, Inject, ViewChild } from '@angular/core';
import {MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import { MatPaginator } from '@angular/material/paginator';
import { MatTableDataSource } from '@angular/material/table';import * as moment from 'moment-timezone';
import { DomSanitizer, SafeHtml } from '@angular/platform-browser';

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

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


@Component({
  selector: 'lot-detail-dialog-dialog',
  templateUrl: './lot-detail-dialog.component.html',
  styleUrls: ['./lot-detail-dialog.component.css']
})
export class LotDetailDialogComponent implements OnInit {
  
  id: string;
  Lot: Lot;  
  
  displayedColumns: string[] = ['amount', 'type', 'time'];
  bids: MatTableDataSource<Bid> = new MatTableDataSource<Bid>();
  @ViewChild(MatPaginator) paginator?: MatPaginator;

  constructor(
    private apiLotService: apiLotService,
    public dialogRef: MatDialogRef<LotDetailDialogComponent>,
    private sanitizer: DomSanitizer,
    @Inject(MAT_DIALOG_DATA) public data: any) {

      this.id = data.id;
      this.Lot = {
        _id: { $oid: '' },
        idPlatform: '',
        platform: '',
        timestamp: '',
        lotNumber: '',
        RawData: {},
        sale_id: { $oid: '' },
        Bids: [],
        title: '',
        description: '',
        auctioned: {
          timestamp: '',
          amount: 0,
          auctioned_type: '',
          sold: false
        }      
      };
    }

  ngOnInit(): void {
    
    this.apiLotService.getLot(this.id).subscribe( Lot => {
      this.Lot = Lot;

      this.bids = new MatTableDataSource(Lot.Bids ?? []);      
      this.bids.paginator = this.paginator ?? null;
    });
  }
  
  getSafeDescription(): SafeHtml {
    if (this.Lot && this.Lot.description) {
      return this.sanitizer.bypassSecurityTrustHtml(this.Lot.description.replace(/\n/g, '<br>'));
    }
    return '';
  }

  cancel(): void {
    this.dialogRef.close(false);
  }

}
