import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { Observable } from 'rxjs';
import { CurrentDeviceService
  , MODBUS_SETTINGS_FIELDS
  , SERIAL_SETTINGS_FIELDS<% if (isProductType('tapnpass')) { %>
  , TAPNPASS_SETTINGS_FIELDS<% } %>
  , ProtocolConfigurationService } from '@iotize/ionic';
import { ToastService } from 'app-theme';

@Component({
  selector: '<%= dasherize(name) %>',
  templateUrl: './<%= dasherize(name) %>.component.html',
  styleUrls: ['./<%= dasherize(name) %>.component.scss'],
})
export class <%= classify(name) %>Component implements OnInit {
  isAdmin: Observable<boolean>;
  
  public SERIAL_SETTINGS_FIELDS = SERIAL_SETTINGS_FIELDS;
  public MODBUS_SETTINGS_FIELDS = MODBUS_SETTINGS_FIELDS;<% if (isProductType('tapnpass')) { %>
  public TAPNPASS_SETTINGS_FIELDS = TAPNPASS_SETTINGS_FIELDS;<% } %>

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

  constructor(private tapService: CurrentDeviceService
    , public protocolSettings: ProtocolConfigurationService
    , private toastService: ToastService) {

    this.isAdmin = this.tapService.sessionState.pipe(
      map(state => state.name === "admin")
    );
  }

  async ngOnInit() {
    this.protocolSettings.errors
      .subscribe((error: Error) => {
        this.onError(error);
      })
  }

  async applyChanges(temporary: boolean) {
    try {
      await this.protocolSettings.applyChanges(temporary);
      // if (this.deviceType == 'tapnpass') {
      //   await this.tapnpass.setTransmissionBufferSize(this.transmissionBufferSize.value);
      // }
    }
    catch (err) {
      this.onError(err);
    }
  }

  private onError(err: Error) {
    this.toastService.error(err);
  }

}
