import { Component, OnInit } from '@angular/core';
import {
  FormBuilder,
  Validators
} from '@angular/forms';

import { EniroStandardData, RegionalData } from './model';

@Component({
  selector: 'example-form',
  template: require('./example-form.component.html'),
  styles:   [require('./example-form.component.scss')]
})
export class ExampleFormComponent implements OnInit {
  public form: any;
  public comunies: any;
  public counties: any;
  public voivodeships: any;
  public countries: any;
  public cities: any;
  public postOffices: any;

  constructor(private fb: FormBuilder) {
    let data: EniroStandardData[] = [
      {
        'company_name':     'Eniro',
        'street':           'Piłsudskiego',
        'house_num':        '23',
        'appartment_num':   '23',
        'district':         'Mokotów',
        'post_office_code': 'Poczta',
        'city':             'Warszawa',
        'city_id':          1,
        'post_office':      'poczta',
        'post_office_id':   1,
        'additional_info':  'cos dodatkowego',
        'county_id':        1,
        'county':           'Limanowski',
        'commune_id':       2,
        'commune':          'Bielany',
        'voivodeship_id':   1,
        'voivodeship':      'Mazowieckie',
        'country_id':       1,
        'country':          'Polska',
        'elid':             1,
        'lastUpdate':       1467808021
      }
    ];
    this.buildForm(data[0]);
  }

  ngOnInit() {
  }

  buildForm(data: EniroStandardData) {

    let controls    = {};
    let notRequired = ['appartment_num', 'district'];
    let notControl  = [
      'commune', 'county', 'country', 'voivodeship',
      'elid', 'city', 'post_office'
    ];
    for (let p in data) {
      if (notControl.includes(p)) continue;
      if (!notRequired.includes(p)) {
        controls[p] = [data[p], Validators.required];
      } else {
        controls[p] = [data[p]];
      }
    }

    this.form = this.fb.group(controls);

    this.comunies     = [];
    this.counties     = [];
    this.voivodeships = [];
    this.countries    = [];
    this.cities       = [];
    this.postOffices  = [];

    this.comunies.push(<RegionalData>{name: data.commune, id: data.commune_id});
    this.counties.push(<RegionalData>{name: data.county, id: data.county_id});
    this.countries.push(<RegionalData>{name: data.country, id: data.country_id});
    this.voivodeships.push(<RegionalData>
      {name: data.voivodeship, id: data.voivodeship_id}
    );
    this.cities.push(<RegionalData>{name: data.city, id: data.city_id});
    this.postOffices.push(<RegionalData>
      {name: data.post_office, id: data.post_office_id}
    );
  }

  onCountyChanged(countyId) { }

  onVoivodeshipChanged(voivodeshipId) { }

  onCountryChanged(countrId) { }

}
