import { Component, Input } from "@angular/core"; import { FormBuilder, FormControl, FormGroup, Validators, } from "@angular/forms"; import { NgbActiveModal } from "@ng-bootstrap/ng-bootstrap"; import { DeviceService } from "../../service/device.service"; @Component({ selector: "app-control-scheduler", templateUrl: "./control-scheduler.component.html", styleUrls: ["./control-scheduler.component.css"], }) export class ControlSchedulerComponent { @Input() deviceId: any; labelModal: string = ""; myForm: FormGroup; dataSwitch = [ { label: "On", value: true, }, { label: "Off", value: false, }, ]; dataActive = [ { label: "Active", value: true, }, { label: "Non Active", value: false, }, ]; daysOfWeek = [ { label: "Monday", value: "monday" }, { label: "Tuesday", value: "tuesday" }, { label: "Wednesday", value: "wednesday" }, { label: "Thursday", value: "thursday" }, { label: "Friday", value: "friday" }, { label: "Saturday", value: "saturday" }, { label: "Sunday", value: "sunday" }, ]; selectedDays: string[] = []; constructor( public activeModal: NgbActiveModal, private fb: FormBuilder, private deviceService: DeviceService ) {} ngOnInit() { this.createForm(); } createForm() { const controls = { name: ["", Validators.required], timeset: ["", Validators.required], active: [true], switch: [false], recurring: [true], // Default value for repeat checkbox device_id: this.deviceId, }; // Initialize checkboxes for each day of the week this.daysOfWeek.forEach((day) => { controls[day.value] = [false]; // Each day starts as unchecked }); this.myForm = this.fb.group(controls); } onDayChange(day: string, isChecked: boolean) { if (isChecked) { this.selectedDays.push(day); } else { this.selectedDays = this.selectedDays.filter((d) => d !== day); } } save() { const formValues = this.myForm.value; // Collect selected days' labels const selectedDays = this.daysOfWeek .filter((day) => formValues[day.value]) .map((day) => day.value); // Construct the final output const result = { name: formValues.name, device_id: formValues.device_id, timeset: formValues.timeset, recurring: formValues.recurring, active: formValues.active, switch: formValues.switch, days: selectedDays, }; if (this.myForm.valid) { this.activeModal.close(result); } else { this.markFormGroupTouched(this.myForm) } // console.log("Form Result: ", result); } markFormGroupTouched(formGroup: FormGroup) { (Object as any).values(formGroup.controls).forEach((control) => { control.markAsTouched(); if (control.controls) { this.markFormGroupTouched(control); } }); } }