import { Component, Input, OnInit } from '@angular/core';
import { FormBuilder, Validators, FormArray} from '@angular/forms';
import { Router } from '@angular/router';
import { Observable, of, pipe } from 'rxjs';
import { City } from 'src/app/models/city';
import { Pump } from 'src/app/models/pump';
import { PumpModel } from 'src/app/models/pumpModel';
import { Wharf } from 'src/app/models/Wharf';
import { WerfFormService } from './werf-form.service';

@Component({
  selector: 'app-werf-form',
  templateUrl: './werf-form.component.html',
  styleUrls: ['./werf-form.component.css'],
})
export class WerfFormComponent implements OnInit {
  // de aan te maken werf
  wharf: Wharf = {
    id: 0,
    nameCode: '',
    cityID: 0,
    streetName: '',
    streetNumber: 0,
    startDate: '',
    endDate: '',
    wharfDepth: 0
  };

  // pomp
  @Input() pump: Pump = {
    id: 0,
    gridPos: '',
    description: '',
    pumpModelID: 0,
    wharfID: 0,
  };

  // pumpmodel
  @Input() pumpModel: PumpModel = {
    id: 0,
    model: '',
    onlyBinary: false
  };

  // city
  @Input() city: City = {
    id: 0,
    postalCode: 0,
    name: ''
  }

  isSubmitted: boolean = false;
  errorMessage: string = "";
  isAdd: boolean = false;
  isEdit: boolean = false;

  wharfId: number = 0;
  wharf$: Observable<Wharf> = new Observable<Wharf>();
  pumps$: Observable<Pump[]> = new Observable<Pump[]>();
  pumpModels$: Observable<PumpModel[]> = new Observable<PumpModel[]>();
  cities$: Observable<City[]> = new Observable<City[]>();

  wharfForm = this.fb.group({
    nameCode: ['', [Validators.required]],
    cityID: [1, [Validators.required]],
    streetName: ['', [Validators.required]],
    streetNumber: [0, [Validators.required]],
    startDate: ["", [Validators.required]],
    endDate: ["", [Validators.required]],
    wharfDepth: [0, [Validators.required]]
  });

  constructor(private router: Router,private fb: FormBuilder, private werfFormService: WerfFormService ) {
    this.isAdd = this.router.getCurrentNavigation()?.extras.state?.['mode'] === 'add';
    this.isEdit = this.router.getCurrentNavigation()?.extras.state?.['mode'] === 'edit';
    this.wharfId = +this.router.getCurrentNavigation()?.extras.state?.['id'];

    if (!this.isAdd && !this.isEdit) {
      this.isAdd = true;
    }

    if (this.wharfId != null && this.wharfId > 0) {
      this.werfFormService.getWharfById(this.wharfId).subscribe(result => {
        this.wharfForm.setValue({
          nameCode: result.nameCode,
          cityID: result.cityID,
          streetName: result.streetName,
          streetNumber: result.streetNumber,
          startDate: this.convertDateFormat(result.startDate),
          endDate: this.convertDateFormat(result.endDate),
          wharfDepth: result.wharfDepth
        });
      });
    }
  }

  convertDateFormat(dateString: string): string {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    return `${year}-${month}-${day}`;
  }



  get f(){
    return this.wharfForm.controls;
  }

  ngOnInit(): void {
    this.pumps$ = this.werfFormService.getPumps();
    this.pumpModels$ = this.werfFormService.getPumptypes();
    this.cities$ = this.werfFormService.getCities();
  }

  LoadDataWharf(){
    this.wharfForm.patchValue({
      streetName: 'straat van werf 1',
    })
  }

  onSubmit(){
    this.isSubmitted = true;

    this.wharf.nameCode = this.wharfForm.value.nameCode!;
    this.wharf.cityID = this.wharfForm.value.cityID!;
    this.wharf.streetName = this.wharfForm.value.streetName!;
    this.wharf.streetNumber = this.wharfForm.value.streetNumber!;
    this.wharf.startDate = this.wharfForm.value.startDate!;
    this.wharf.endDate = this.wharfForm.value.endDate!;
    this.wharf.wharfDepth = this.wharfForm.value.wharfDepth!;
    this.wharf.cityID = this.wharfForm.value.cityID!;

    console.log(this.wharf);

   if (this.isAdd) {
      return this.werfFormService.postWharf(this.wharf).subscribe((result) => {
        this.router.navigateByUrl('/admin/werf/form2/' + result);
      });
   }
    if (this.isEdit) {
      this.wharf.id = this.wharfId;
      return this.werfFormService.putWharf(this.wharf, this.wharf.id).subscribe((result) => {
        this.router.navigateByUrl('/admin/werf/form2/' + this.wharfId);
      });
    } else {
      return this.werfFormService.postWharf(this.wharf).subscribe((result) => {
        this.router.navigateByUrl('/admin/werf/form2/' + result.id);
      });
    }
  }

  overzicht(){
    this.router.navigateByUrl('/overzicht_werven');
  }
}
