import { PropertyValues } from "lit";
import { property } from "lit/decorators.js";
import { RequestAuthorizationKind, IBasicAuthorization, ApiDefinitions, IRequestAuthorization } from "@api-client/core/build/browser.js";
import BasicAuthorization from "../../authorization/ui/BasicAuthorization.js";
import * as InputCache from '../../../amf/lib/InputCache.js';

export default class AmfBasic extends BasicAuthorization {
  /**
   * The in-memory key where the values are stored.
   */
  @property({ type: Object }) security?: ApiDefinitions.IApiParametrizedSecurityScheme;

  protected override willUpdate(cp: PropertyValues<this>): void {
    if (cp.has('security')) {
      this.restoreValues();
    }
    super.willUpdate(cp);
  }

  protected ensureConfig(): IRequestAuthorization {
    if (!this.authorization) {
      this.authorization = {
        enabled: true,
        kind: RequestAuthorizationKind,
        type: 'basic',
        valid: false,
        config: {
          username: '',
        } as IBasicAuthorization,
      };
    }
    return this.authorization;
  }

  protected restoreValues(): void {
    const auth = this.ensureConfig();
    const config = auth.config as IBasicAuthorization;
    if (config.username || config.password) {
      return;
    }
    const { security } = this;
    if (!security) {
      return;
    }
    const restore = InputCache.get(this, security.id, true) as IBasicAuthorization | undefined;
    if (!restore) {
      return;
    }
    auth.config = restore;
    this.requestUpdate();
  }

  protected override handleUsername(e: Event): void {
    const { security } = this;
    if (!security) {
      return;
    }
    const auth = this.ensureConfig();
    super.handleUsername(e);
    InputCache.set(this, security.id, auth.config, true);
  }

  protected override handlePassword(e: Event): void {
    const { security } = this;
    if (!security) {
      return;
    }
    const auth = this.ensureConfig();
    super.handlePassword(e);
    InputCache.set(this, security.id, auth.config, true);
  }
}
