import {Component, inject, input, signal} from '@angular/core';
import {NetworkStorage} from '../../../../service-manager';
import {
  TuiAlertService,
  TuiButton,
  TuiDialog,
  TuiErrorComponent,
  TuiGroup,
  TuiIcon,
  TuiInputDirective
} from '@taiga-ui/core';
import {TranslatePipe} from '@ngx-translate/core';
import {Oimg} from '../../../elements/oimg/oimg';
import {environment} from '../../../../../environments/environment';
import {TuiButtonLoading, TuiComboBox} from '@taiga-ui/kit';

@Component({
  selector: 'network-settings-overview',
  imports: [
    TuiGroup,
    TranslatePipe,
    TuiIcon,
    Oimg,
    TuiButton,
    TuiDialog,
    TuiComboBox,
    TuiInputDirective,
    TuiButtonLoading,
    TuiErrorComponent
  ],
  templateUrl: './overview.html',
  styleUrl: './overview.scss',
})
export class Overview {
  networkStore = input.required<NetworkStorage>()
  protected readonly environment = environment;
  protected readonly localStorage = localStorage;

  setNewNameDialogOpen = signal(false)
  setNewNamePending = signal(false)
  setNewNameError = signal("")

  makeNetworkPrivateWarnDialogOpen = signal(false)
  makeNetworkPublicWarnDialogOpen = signal(false)
  networkVisChangePending = signal(false)

  async setNewName(name: string) {
    this.setNewNameError.set("")
    this.setNewNamePending.set(true)
    try {
      await this.networkStore().service.editName(name)
      this.setNewNamePending.set(false)
      this.setNewNameDialogOpen.set(false)
      this.networkStore().networkData.update(
        value => {
          value.name = name
          return value
        }
      )
    } catch (e) {
      this.setNewNamePending.set(false)
      this.setNewNameError.set(e as string)
    }
  }

  async changeVisibility(newVisibility: "public" | "private") {
    this.networkVisChangePending.set(true)
    await this.networkStore().service.changeVisibility(newVisibility)
    this.networkStore().networkData.update(
      value => {
        value.visibility = newVisibility
        return value
      }
    )
    this.networkVisChangePending.set(false)
    this.makeNetworkPrivateWarnDialogOpen.set(false)
    this.makeNetworkPublicWarnDialogOpen.set(false)
  }
}
