import {AuthorizationRequestHandler} from '@openid/appauth';
import {
  StorageBackend,
  Requestor,
  AuthorizationServiceConfiguration,
  LocalStorageBackend,
  JQueryRequestor,
  TokenRequestHandler,
} from '@openid/appauth';
import {
  UserInfoHandler,
  EndSessionHandler,
  Browser,
  DefaultBrowser,
  AuthService,
  AuthActionBuilder,
} from 'ionic-appauth';

const TOKEN_RESPONSE_KEY = 'token_response';

export class DefaultAuthService extends AuthService {
  public localConfiguration: AuthorizationServiceConfiguration;

  protected tokenHandler: TokenRequestHandler;

  protected userInfoHandler: UserInfoHandler;

  protected requestHandler: AuthorizationRequestHandler;

  protected endSessionHandler: EndSessionHandler;

  constructor(
    protected browser: Browser = new DefaultBrowser(),
    protected storage: StorageBackend = new LocalStorageBackend(),
    protected requestor: Requestor = new JQueryRequestor(),
  ) {
    super(browser, storage, requestor);
  }

  get configuration(): Promise<AuthorizationServiceConfiguration> {
    if (!this.localConfiguration)
      throw new Error('Local Configuration Not Defined');

    return Promise.resolve(this.localConfiguration);
  }

  public async signOut() {
    await this.storage.removeItem(TOKEN_RESPONSE_KEY).catch(error => {
      this.notifyActionListers(AuthActionBuilder.SignOutFailed(error));
    });
    this.notifyActionListers(AuthActionBuilder.SignOutSuccess());
  }
}
