| 1 | /* |
| 2 | * Copyright (c) 2024 sovity GmbH |
| 3 | * |
| 4 | * This program and the accompanying materials are made available under the |
| 5 | * terms of the Apache License, Version 2.0 which is available at |
| 6 | * https://www.apache.org/licenses/LICENSE-2.0 |
| 7 | * |
| 8 | * SPDX-License-Identifier: Apache-2.0 |
| 9 | * |
| 10 | * Contributors: |
| 11 | * sovity GmbH - initial implementation |
| 12 | */ |
| 13 | import {Component, Input, OnDestroy, OnInit} from '@angular/core'; |
| 14 | import {Subject, takeUntil} from 'rxjs'; |
| 15 | import {Store} from '@ngxs/store'; |
| 16 | import {DeploymentEnvironmentDto} from '@sovity.de/authority-portal-client'; |
| 17 | import {GlobalState} from 'src/app/core/global-state/global-state'; |
| 18 | import {SwitchEnvironment} from 'src/app/core/global-state/global-state-actions'; |
| 19 | import {GlobalStateUtils} from 'src/app/core/global-state/global-state-utils'; |
| 20 | |
| 21 | @Component({ |
| 22 | selector: 'app-env-switcher', |
| 23 | templateUrl: './env-switcher.component.html', |
| 24 | }) |
| 25 | export class EnvSwitcherComponent implements OnInit, OnDestroy { |
| 26 | @Input() deploymentEnvironments: DeploymentEnvironmentDto[] = []; |
| 27 | |
| 28 | selectedEnvironmentId!: string; |
| 29 | state!: GlobalState; |
| 30 | |
| 31 | private ngOnDestroy$ = new Subject(); |
| 32 | |
| 33 | constructor( |
| 34 | public store: Store, |
| 35 | private globalStateUtils: GlobalStateUtils, |
| 36 | ) {} |
| 37 | |
| 38 | ngOnInit(): void { |
| 39 | this.listenToAvailableEnvironments(); |
| 40 | this.setDefaultEnvironment(); |
| 41 | } |
| 42 | |
| 43 | selectEnvironment(environment: DeploymentEnvironmentDto) { |
| 44 | this.selectedEnvironmentId = environment.environmentId; |
| 45 | this.store.dispatch(new SwitchEnvironment(environment)); |
| 46 | } |
| 47 | |
| 48 | private listenToAvailableEnvironments() { |
| 49 | this.globalStateUtils |
| 50 | .getDeploymentEnvironments() |
| 51 | .subscribe((environments: DeploymentEnvironmentDto[]) => { |
| 52 | this.deploymentEnvironments = environments; |
| 53 | }); |
| 54 | } |
| 55 | |
| 56 | private setDefaultEnvironment() { |
| 57 | this.globalStateUtils |
| 58 | .getDeploymentEnvironmentId() |
| 59 | .pipe(takeUntil(this.ngOnDestroy$)) |
| 60 | .subscribe((environmentId: string) => { |
| 61 | this.selectedEnvironmentId = environmentId; |
| 62 | }); |
| 63 | } |
| 64 | |
| 65 | ngOnDestroy(): void { |
| 66 | this.ngOnDestroy$.next(null); |
| 67 | this.ngOnDestroy$.complete(); |
| 68 | } |
| 69 | } |