import { Component, Input, OnDestroy, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Observable, Subscription } from 'rxjs';
import { Pump } from 'src/app/models/pump';
import { WerfFormThreeService } from './werf-form-three.service';
import { CdkDragDrop, moveItemInArray } from '@angular/cdk/drag-drop';
import { Sensor } from 'src/app/models/sensor';
import { Router } from '@angular/router';
import { SensorPump } from 'src/app/models/sensorPump';

@Component({
  selector: 'app-werf-form-three',
  templateUrl: './werf-form-three.component.html',
  styleUrls: ['./werf-form-three.component.css']
})
export class WerfFormThreeComponent implements OnInit, OnDestroy {
  // pomp
  @Input() pump: Pump = {
    id: 0,
    gridPos: '',
    description: '',
    pumpModelID: 0,
    wharfID: 0
  };

  // sensor
  @Input() sensor: Sensor = {
    id: 0,
    gridPos: '',
    description: '',
    batteryPercentage: 0,
    wharfID: 0
  }

  // sensorPump
  @Input() sensorPump: SensorPump = {
    id: 0,
    sensorID: 0,
    pumpID: 0,
    priority: 0
  }


  wharfId: number = 0;
  errorMessage: string = '';

  pumps$: Observable<Pump[]> = new Observable<Pump[]>();
  // sensors$: Observable<any[]> = new Observable<any[]>();
  sensors$: any;

  postSensorPump$: Subscription = new Subscription();

  constructor(private werfFormThreeService: WerfFormThreeService,
    private route: ActivatedRoute,
    private router: Router) { }

  ngOnInit(): void {
    this.wharfId = parseInt(JSON.parse(this.route.snapshot.paramMap.get('wharfIid') || '{}'));
    this.pumps$ = this.werfFormThreeService.getPumps();
    this.sensors$ = this.werfFormThreeService.getSensors();
  }

  ngOnDestroy(): void {
    this.postSensorPump$.unsubscribe();
  }

  changePriority(pumpId: number, sensorId: number, event: any) {
    this.sensorPump.sensorID = sensorId;
    this.sensorPump.pumpID = pumpId;
    this.sensorPump.priority = Number((event.target as HTMLInputElement).value);
    this.postSensorPump$ = this.werfFormThreeService.postSensorPump(this.sensorPump).subscribe({
      error: (e) => this.errorMessage += e.message
    });
    console.log(this.sensorPump);
  }

  next(){
    this.router.navigateByUrl('/admin/werf/form4/' + this.wharfId);
  }

  back(){
    this.router.navigateByUrl('/admin/werf/form2/' + this.wharfId);
  }

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

}

