import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { NbMenuItem } from '@nebular/theme';
import { first } from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { IGamePlayer } from '../games/games.model';
import { LoginUserService } from './login-user.service';
import { SignalRMessage, SignalRService } from './signal-r.service';
const GAME_ROOM_URL = `${environment.apiUrl}/api/GameRoom`
const GAME_ROOM_Message_URL = `${environment.apiUrl}/api/GameRoomMessage`
@Injectable({
  providedIn: 'root'
})
export class GameRoomService {
  gameRoomId: string;
  sideMenu: NbMenuItem[] = [];
  constructor(
    private http: HttpClient,
    private loginUserService: LoginUserService,
    private signalRService: SignalRService
  ) { }
  currentPlayer() {
    return {
      name: this.loginUserService.userAccess.firstName,
      id: this.loginUserService.userAccess.memberId,
      signalRClientId: this.loginUserService.userAccess.signalRConnectionId,
      isPlayer: true,
      gameRoomId: this.gameRoomId,
      tabId: this.loginUserService.sessionTabId
    } as IGamePlayer;
  }
  createGameRoom(name: string) {
    //Using current player to create game room
    let currentPlayer = this.currentPlayer();
    currentPlayer.gameRoomId = currentPlayer.id;
    this.gameRoomId = currentPlayer.id;
    this.http.post<boolean>(GAME_ROOM_URL,
      JSON.stringify(currentPlayer), {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    }).pipe(first()).subscribe(result => {
      this.signalRService.startSignalRConnection(this.gameRoomId);
    });
  }

  joinGameRoom(roomId: string) {
    this.http.put<boolean>(GAME_ROOM_URL + '\\' + roomId,
      JSON.stringify(this.currentPlayer()), {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    }).pipe(first()).subscribe(result => {
      this.gameRoomId = roomId;
      this.signalRService.startSignalRConnection(this.gameRoomId);
    });
  }
  sendMessage(data: SignalRMessage) {
    return this.http.post<boolean>(GAME_ROOM_Message_URL,
      JSON.stringify(data), {
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
      },
    });
  }

}
