import {Component, inject, OnInit, signal} from '@angular/core';
import {ActivatedRoute, RouterLink, RouterOutlet} from '@angular/router';
import {Chat} from '@chatenium/chatenium-sdk/domain/chatService.schema';
import {Message} from '@chatenium/chatenium-sdk/domain/dmService.schema';
import {MessageBoxViewModel} from '../elements/message-box/message-box-viewmodel';
import {DmStorage, NetworkStorage, ServiceManager} from '../../service-manager';
import {DMService} from '@chatenium/chatenium-sdk/services/dmService';
import {Network as NetworkData} from "@chatenium/chatenium-sdk/domain/networkService.schema"
import {NetworkService} from '@chatenium/chatenium-sdk/services/networkService';
import {IndexedDB} from '../../storage/indexed-db';
import {Navbar} from '../elements/navbar/navbar';
import {Oimg} from '../elements/oimg/oimg';
import {TUI_BREAKPOINT, TuiButton, TuiGroup, TuiIcon} from '@taiga-ui/core';

@Component({
  selector: 'app-network',
  imports: [
    RouterOutlet,
    Navbar,
    Oimg,
    TuiGroup,
    TuiButton,
    TuiIcon,
    RouterLink
  ],
  templateUrl: './network.html',
  styleUrl: './network.scss',
})
export class Network implements OnInit {
  serviceManager = inject(ServiceManager)
  route = inject(ActivatedRoute)
  indexedDb = inject(IndexedDB)
  breakpoint = inject(TUI_BREAKPOINT)

  routerOutletActive = signal(false)

  networkId = ""
  get store() {
    return this.serviceManager.networkServices()[this.networkId]
  }

  ngOnInit() {
    this.route.params.subscribe(async params => {
      console.log("Loading network...")
      const networkId = params['networkId'];
      this.networkId = networkId;

      const session = this.serviceManager.currentSession();
      const networkData = this.serviceManager.networks().find(c => c.networkId === networkId);

      if (!session || !networkData) {
        console.warn(`Initialization deferred for ${networkId}: Session or NetworkData missing.`);
        return;
      }

      if (!this.serviceManager.networkServices()[networkId]) {
        const newStore = {
          networkData: signal<NetworkData>(networkData),
          textChannels: signal({}),
          wsListener: (action, data) => {
          },
        } as NetworkStorage;

        newStore.service = new NetworkService(
          session.userData.userid,
          session.token,
          networkId,
          this.indexedDb.getApi(),
          (action, data) => newStore.wsListener(action, data)
        );

        this.serviceManager.networkServices()[networkId] = newStore;
      }
    });
  }
}
