import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { TokenStorageService } from './token.service';

const API_URL = 'https://gruppe1.testsites.info/api/';

@Injectable({
  providedIn: 'root',
})
export class BotService {
  constructor(
    private http: HttpClient,
    private tokenStorage: TokenStorageService
  ) {}

  /**
   * Function to get all keywords
   * @returns Observable
   */
  public getKeywords(): Observable<any> {
    return this.http.get(API_URL + 'keywords', {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + this.tokenStorage.getToken(),
      }),
      responseType: 'text',
    });
  }

  /**
   * Function to create a keyword
   * @param  {string} keyword
   * @returns Observable
   */
  public createKeyword(keyword: string): Observable<any> {
    return this.http.post(
      API_URL + 'keyword',
      {
        keyword,
      },
      {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + this.tokenStorage.getToken(),
        }),
      }
    );
  }

  /**
   * Function to delete a keyword
   * @param  {string} keyword
   * @returns Observable
   */
  public deleteKeyword(keyword: string): Observable<any> {
    return this.http.delete(API_URL + 'keyword', {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + this.tokenStorage.getToken(),
      }),
      body: {
        keyword,
      },
    });
  }

  /**
   * Function to get all shares
   * @returns Observable
   */
  public getSymbols(): Observable<any> {
    return this.http.get(API_URL + 'shares', {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + this.tokenStorage.getToken(),
      }),
      responseType: 'text',
    });
  }

  /**
   * Function to create a share
   * @param  {string} keyword
   * @returns Observable
   */
  public createShare(isin: string, comment: string): Observable<any> {
    return this.http.post(
      API_URL + 'share',
      {
        comment,
        isin,
      },
      {
        headers: new HttpHeaders({
          'Content-Type': 'application/json',
          Authorization: 'Bearer ' + this.tokenStorage.getToken(),
        }),
      }
    );
  }

  /**
   * Function to delete a share
   * @param  {string} isin
   * @returns Observable
   */
  public deleteShare(isin: string): Observable<any> {
    return this.http.delete(API_URL + 'share', {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
        Authorization: 'Bearer ' + this.tokenStorage.getToken(),
      }),
      body: {
        isin,
      },
    });
  }
}
