import { Injectable } from '@angular/core';
import { map, catchError } from 'rxjs/operators';
import { Observable, of } from 'rxjs';
import { ResponseArgs } from '@swagger/cat';
import { UserStateService as UserStateServiceAPI } from '@swagger/isa';
import { UserState, ResponseArgsOfUserState } from '@swagger/isa';

@Injectable({
  providedIn: 'root',
})
export class UserStateService {
  constructor(private userStateService: UserStateServiceAPI) {}

  saveUserState(userData: string): Observable<string> {
    const us: UserState = {
      content: userData,
    };

    return this.userStateService.UserStateSetUserState(us).pipe(
      map((response: ResponseArgs) => {
        if (response.error) {
          console.error(response.message);
        }

        return response.message;
      })
    );
  }

  getUserState(): Observable<any> {
    return this.userStateService.UserStateGetUserState().pipe(
      catchError(() => {
        return of(undefined);
      }),
      map((response: ResponseArgsOfUserState) => {
        if (!response) {
          return;
        }
        if (response.error) {
          console.error(response.message);
        }

        return response.result;
      })
    );
  }

  async resetState() {
    await this.userStateService
      .UserStateResetUserState()
      .pipe(
        map((response: ResponseArgsOfUserState) => {
          if (response.error) {
            console.error(response.message);
          }

          return response.result;
        })
      )
      .toPromise();
  }
}
