import { Component, OnInit, OnDestroy } from '@angular/core';
import { CurrentDeviceService, TapInfo } from '@iotize/ionic';
import { ConnectionStateChangeEvent, ConnectionState } from '@iotize/device-client.js/protocol/api';
import { Subscription } from 'rxjs';
import { ModalController } from '@ionic/angular';
import { TapMonitoringSettingsComponent, MonitoringSettingsService } from '@iotize/ionic';
import { <%= classify(appName) %> } from '<%= tapApiImportPath %>';

@Component({
  selector: '<%= dasherize(name) %>',
  templateUrl: './<%= dasherize(name) %>.component.html',
  styleUrls: ['./<%= dasherize(name) %>.component.scss'],
})
export class <%= classify(name) %>Component implements OnInit, OnDestroy {
  private connectionStateChangeSub: Subscription;
  private monitoringSettingsSub: Subscription;

  waitForSubmit: boolean = false;
  isMonitorRunning: boolean = false;
  data ?: <%= classify(appName) %>.DataManager;

  constructor(private tapService: CurrentDeviceService
    , private modalController: ModalController
    , private monitoringSettingsService: MonitoringSettingsService) {
  }

  async ngOnInit() {
    this.data = <%= classify(appName) %>.DataManager.create(this.tapService.tap);
    
    this.waitForSubmit = !this.tapService.tap.isConnected();

    this.connectionStateChangeSub = this.tapService
      .connectionState
      .subscribe((event: ConnectionStateChangeEvent) => {
        switch (event.newState) {
          case ConnectionState.CONNECTED:
            this.waitForSubmit = false;
            break;
          default:
            this.waitForSubmit = true;
        }
      });
      
    this.monitoringSettingsSub = this.monitoringSettingsService
      .settings$
      .subscribe((newSettings) => {
        this.data.setMonitoringPeriod(newSettings.period);
      });

    this.startMonitor();
  }

  ngOnDestroy() {
    this.connectionStateChangeSub.unsubscribe();
    this.monitoringSettingsSub.unsubscribe();
  }
  
  get variables() {
    return this.data.variables;
  }

  get tap() {
    return this.tapService.tap;
  }

  get isMonitoringRunning(){
    return this.data && this.data.isMonitoringRunning;
  }

  stopMonitor() {
    this.data.stopAll();
  }

  async startMonitor() {
    await this.tap.service.target.connect().catch((err) => console.warn(err));
    this.data.startAll(
      this.monitoringSettingsService.settings.period
    );
  }

  async openSettings() {
    const modal = await this.modalController.create({
      component: TapMonitoringSettingsComponent,
    });

    return await modal.present();
  }
}
