import { Component, Input, OnInit, ViewEncapsulation } from '@angular/core';
import { UntypedFormBuilder } from '@angular/forms';
import { RegionService } from '@shared/ui-api/region.service';

@Component({
  selector: 'app-region-selector',
  templateUrl: './region-selector.component.html',
  styleUrls: ['./region-selector.component.scss'],
  encapsulation: ViewEncapsulation.None,
})
export class RegionSelectorComponent implements OnInit {
  @Input() regionSelectorDefaultRegionKey: string = null;

  regionSelectForm = this.formBuilder.group({
    region: [''],
  });

  constructor(
    private formBuilder: UntypedFormBuilder,
    public regionService: RegionService,
  ) {
  }

  ngOnInit(): void {
    this.regionService.getSelectedRegion(this.regionSelectorDefaultRegionKey).subscribe(selectedRegion => {
      this.regionSelectForm.setValue({region: selectedRegion});

      this.regionSelectForm.controls.region.valueChanges.subscribe(newRegion => {
        this.regionService.setRegion(newRegion);
      });
    });
  }
}
