import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
import {HttpClient} from '@angular/common/http';
import {Token} from './token';
import {Setting} from './setting';
import {ChatMessage} from './chat.message';
import {ChatTokenResponse} from './chat.token';
import {VersionInfo} from './version.info';

@Injectable({
  providedIn: 'root'
})
export class ApiService {
  public static userToken: string;

  constructor(private client: HttpClient) {
  }

  getAuthToken(username: string, password: string): Observable<Token> {
    return this.client.post<Token>(Setting.URL + '/token', {username, password});
  }

  getChatToken(authToken: string): Observable<ChatTokenResponse> {
    return this.client.get<ChatTokenResponse>(
      Setting.URL + '/session/chat',
      {headers: {Authorization: 'Bearer ' + authToken}}
      );
  }

  getChatHistory(token: string, offset: number, limit: number): Observable<ChatMessage[]> {
    return this.client.get<ChatMessage[]>(
      Setting.URL + '/session/chat/history?limit=' + limit + '&offset=' + offset + (Setting.DEBUG ? '&debug=true' : ''),
      {headers: {Authorization: 'Bearer ' + token}}
    );
  }

  getChatMessagesMissed(token: string, lastMessageId: number): Observable<ChatMessage[]> {
    return this.client.get<ChatMessage[]>(
      Setting.URL + '/session/chat/history/missed?lastMessageId=' + lastMessageId,
      {headers: {Authorization: 'Bearer ' + token}}
    );
  }

  deleteAuthToken(token: string): Observable<string>
  {
    return this.client.delete<string>(
      Setting.URL + '/token/' + token,
      {headers: {Authorization: 'Bearer ' + token}}
      );
  }

  getCurrentVersion(): Observable<VersionInfo>
  {
    return this.client.get<VersionInfo>(Setting.URL + '/metasocket/info');
  }
}
