import { Component, OnInit, Inject } from '@angular/core';
import {MatDialogRef, MAT_DIALOG_DATA} from '@angular/material/dialog';
import * as moment from 'moment-timezone';

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

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


@Component({
  selector: 'loading-sale-dialog-dialog',
  templateUrl: './loading-sale-dialog.component.html',
  styleUrls: ['./loading-sale-dialog.component.css']
})
export class LoadingSaleDialogComponent implements OnInit {
  
  url: string = '';
  SaleInfo: SaleInfo;
  date: Date;
  hour: string = "";

  constructor(
    private apiSaleService: apiSaleService,
    public dialogRef: MatDialogRef<LoadingSaleDialogComponent>,
    @Inject(MAT_DIALOG_DATA) public data: any) {
      this.SaleInfo = {
        _id: "",
        idPlatform: "",
        platform: "",        
        url: "",
        title: "",
        date: "",
        location: "",
        saleHouseName: "",
        status: ""
      };
      this.date = new Date();
    }

  ngOnInit(): void {
    this.url = this.data.url;
    console.log(this.url);   
    
    this.apiSaleService.getSaleInfos(this.url).subscribe( SaleInfo => {
      console.log(SaleInfo);
      this.SaleInfo = SaleInfo;       

      //hour    
      // Europe/Paris is the timezone of the user      
      this.date = moment(this.SaleInfo.date).tz('Europe/Paris').toDate();
      this.hour = moment(this.SaleInfo.date).tz('Europe/Paris').format('HH:mm'); 
      
      }
    );
  }

  save(): void {
    const Sale: Sale = {
      _id: { $oid: '' },
      idPlatform: this.SaleInfo.idPlatform,
      platform: this.SaleInfo.platform,
      url: this.SaleInfo.url,
      title: this.SaleInfo.title,
      date: this.SaleInfo.date,
      location: this.SaleInfo.location,
      saleHouseName: this.SaleInfo.saleHouseName,
      status: "ready"
    }

    this.apiSaleService.saveSale(Sale).subscribe( Sale => {
      this.dialogRef.close(true);
    });
  }

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

}
