import {Component, inject, signal} from '@angular/core';
import {DmStorage, PictureStorage, ServiceManager} from '../../../service-manager';
import {ActivatedRoute} from '@angular/router';
import {IndexedDB} from '../../../storage/indexed-db';
import {TUI_BREAKPOINT, TuiButton, TuiIcon} from '@taiga-ui/core';
import {PictureService} from '@chatenium/chatenium-sdk/services/pictureService';
import {Navbar} from '../../elements/navbar/navbar';
import {Oimg} from '../../elements/oimg/oimg';
import {Masonry} from '../../elements/masonry/masonry';

@Component({
  selector: 'app-see',
  imports: [
    Navbar,
    Oimg,
    TuiButton,
    TuiIcon,
    Masonry
  ],
  templateUrl: './see.html',
  styleUrl: './see.scss',
})
export class See {
  serviceManager = inject(ServiceManager)
  route = inject(ActivatedRoute)
  indexedDb = inject(IndexedDB)
  breakpoint = inject(TUI_BREAKPOINT)

  uploaderId = ""

  get store(): PictureStorage {
    return this.serviceManager.pictureServices()[this.uploaderId]
  }

  ngOnInit() {
    this.route.params.subscribe(async params => {
      const uploaderId = params['uploaderId'];
      this.uploaderId = uploaderId;

      const session = this.serviceManager.currentSession();
      if (!session) {
        return
      }

      if (!this.serviceManager.pictureServices()[uploaderId]) {
        const newService = new PictureService(
          session.token,
          uploaderId,
          session.userData.userid,
          this.indexedDb.getApi(),
        );

        const uploaderInfo = await newService.get()

        this.serviceManager.pictureServices.update(services => ({
          ...services,
          [uploaderId]: {
            albums: signal(uploaderInfo.pictures),
            uploaderData: signal(uploaderInfo.userData),
            service: newService,
          } as PictureStorage
        }));
      }
    });
  }
}
