import { Component, OnInit } from '@angular/core';
import { AuthService } from 'src/app/services/auth.service';
import { UsersService } from 'src/app/services/users.service';
import { User } from '../../../models/userResponse';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { Tirage} from 'src/app/models/tirage';
import { MatSnackBar } from '@angular/material/snack-bar';

interface httpResponse {
  message: string,
  success: boolean,

}

@Component({
  selector: 'app-tirage',
  templateUrl: './tirage.component.html',
  styleUrls: ['./tirage.component.scss']
})
export class TirageComponent implements OnInit {

  private readonly URL = "http://localhost:4000"
  user: User
  formTirage: FormGroup
  messageError: string = null 
  tirage: httpResponse = {
    message: '',
    success: false,
  }
  constructor(private authService : AuthService, private userService : UsersService, private fb : FormBuilder, private http: HttpClient, private snackbar: MatSnackBar) { }

  ngOnInit(): void {
    this.authService.getUserInfo().subscribe(user => this.user = user)
    this.createdForm()
  }

  createdForm() {
    this.formTirage = this.fb.group({
      date: ['', Validators.required]
    })
  }

  postDateTirage() {
    console.log('date: ', this.formTirage.value)
    const tiragedate = this.formTirage.value as Date
    const reponse  = this.http.post<httpResponse>(`${this.URL}/api/tirage/date`, tiragedate)
    reponse.toPromise().then( res => {
      this.snackbar.open(res.message, 'close')
    }).catch(err => {
      console.log('message erreur =>', err.error.message)
      this.messageError = err.error.message
    })

  }
  
  getTirage() {
    const resultatTirage = this.http.get<httpResponse>(`${this.URL}/api/tirage`)
    resultatTirage.toPromise().then(
      (res) =>  {
      this.tirage = res
      console.log('resultar ', this.tirage)
      }
    ).catch(
      err => console.log('err', err)
    )
  }

  getWinner(user: User) {

  }

}
