import { Component, Input, OnInit, OnDestroy, inject } from "@angular/core";
import { FormGroup } from "@angular/forms";
import { Subject, Subscription, combineLatest } from "rxjs";
import { SamPageNextService } from "../../experimental/patterns/layout/architecture";
import { areEqual } from "../../utilities";
@Component({
selector: "sam-filters-wrapper",
template: `
`,
standalone: false,
})
export class SamFiltersWrapperComponent implements OnInit, OnDestroy {
private _service = inject(SamPageNextService, { optional: true });
/**
* Sets primary button text submitting the form
*/
@Input() public runBtnText: string = "Run Report";
/**
* Sets secondary button text for resetting the form
*/
@Input() public resetBtnText: string = "Reset Report";
/**
* Passes in the required form group
*/
@Input() public group: FormGroup;
/**
* Disables the primary button text
*/
@Input() public disabled = false;
public runReportEvent = new Subject();
public resetReportEvent = new Subject();
public disableAction = false;
private _runReportSubscription: Subscription;
private _resetReportSubscription: Subscription;
private _filtersSubscription: Subscription;
public ngOnInit() {
this._initializeService();
this._initializeHandlers();
}
public ngOnDestroy() {
if (this._runReportSubscription) {
this._runReportSubscription.unsubscribe();
}
if (this._service && this._filtersSubscription) {
this._filtersSubscription.unsubscribe();
}
if (this._resetReportSubscription) {
this._resetReportSubscription.unsubscribe();
}
}
private _initializeHandlers() {
this._runReportSubscription = this.runReportEvent.subscribe(() => {
if (this._service) {
this._service.model.properties["filters"].setValue(this.group.value);
}
});
this._resetReportSubscription = this.resetReportEvent.subscribe(
this._clearModel.bind(this)
);
}
private _clearModel() {
const cleared = {};
Object.keys(this.group.value).forEach((key) => (cleared[key] = null));
if (this._service) {
this._service.model.properties["filters"].setValue(cleared);
}
}
private _initializeService() {
if (this._service) {
combineLatest(
this.group.valueChanges,
this._service.model.properties["filters"].valueChanges
).subscribe((changes) => {
if (areEqual(changes[0], changes[1])) {
this.disableAction = true;
} else {
this.disableAction = false;
}
});
// Add initial form model to data structure
this._service.model.properties["filters"].setValue(this.group.value);
// Listen for external changes to value and update form
this._filtersSubscription = this._service.model.properties[
"filters"
].valueChanges.subscribe((event) => {
try {
this.group.setValue(event, { emitEvent: false });
} catch {
return;
}
});
}
}
}