import {Component, OnInit} from '@angular/core';
import {RestService} from '../../services/rest.service';
import {WebsocketService} from '../../services/websocket.service';
import {NGXLogger} from 'ngx-logger';
import {Subscription} from 'rxjs';

@Component({
  selector: 'app-landing',
  templateUrl: './landing.component.html',
  styleUrls: ['./landing.component.css']
})
export class LandingComponent implements OnInit {

  private wsSubscription: Subscription;
  private wsMessageCounter: number;
  exampleInputText: string;
  showPar = false;
  testList = [{'value': 1}, {'value': 2}, {'value': 3}];
  myValue: any = 15;

  constructor(
    private logger: NGXLogger,
    private restService: RestService,
    private wsService: WebsocketService
  ) {
  }

  ngOnInit(): void {
    // perform test rest call as observable
    this.observableCall();

    // perform test rest call as promise (shorter - will only be executed exactly once)
    this.promiseCall();

    // perform test ws send / receive
    setTimeout(() => {
        this.wsCall();
      },
      1000);
  }

  private observableCall(): void {

    const subscription = this.restService.testCall(1).subscribe(
      // subscribe with lambda function
      response => {
        this.logger.debug('Execute obs test call', response);
        subscription.unsubscribe();
      },
      error => {
        this.logger.error('Error while executing obs test call', error);
        subscription.unsubscribe();
      }
    );
  }

  private promiseCall(): void {
    this.restService.testCall(2).toPromise()
      // lambda for success
      .then(response => {
        this.logger.debug('Execute obs test call', response);
      })
      // lambda for fail
      .catch(error => {
        this.logger.error('Error while executing obs test call', error);
      });
  }

  private wsCall(): void {
    this.wsMessageCounter = 0;
    this.wsSubscription = this.wsService.wsTestCall('Test message').message.subscribe(
      result => {
        this.logger.debug('ws call result', result);
        if (this.wsMessageCounter >= 2) {
          this.wsSubscription.unsubscribe();
        }
      },
      error => {
        this.logger.error('ws call error', error);
        this.wsSubscription.unsubscribe();
      }
    );
  }

  alert() {
    alert(this.exampleInputText);
  }
}
