import {Component, Input, OnInit} from '@angular/core';
import {ModalController} from '@ionic/angular';
import {ApiService} from '../../../service/api.service';
import {Observable} from 'rxjs';

@Component({
  selector: 'app-selector',
  templateUrl: './selector.component.html',
  styleUrls: ['./selector.component.scss'],
})
export class SelectorComponent implements OnInit {
  @Input() node: any;
  public sharingInfo: {
    view: Array<{username: string, id: string, level: 'view'|'update'|'manage'}>,
    update: Array<{username: string, id: string, level: 'view'|'update'|'manage'}>,
    manage: Array<{username: string, id: string, level: 'view'|'update'|'manage'}>,
  } = {view: [], update: [], manage: []};
  public generatedLink = '';

  constructor(
      protected modals: ModalController,
      protected api: ApiService,
  ) {}

  public get title() {
    return this.node ? `Share ${this.node.name}` : 'Manage Sharing';
  }

  public get isShared() {
    return (this.sharingInfo.view.length > 0) || (this.sharingInfo.update.length > 0) || (this.sharingInfo.manage.length > 0);
  }

  ngOnInit() {
    this.loadShareInfo().subscribe(data => {
      this.sharingInfo = data;
    });
  }

  dismissModal(success: boolean) {
    this.modals.dismiss();
  }

  loadShareInfo(): Observable<{
    view: Array<{username: string, id: string, level: 'view'|'update'|'manage'}>,
    update: Array<{username: string, id: string, level: 'view'|'update'|'manage'}>,
    manage: Array<{username: string, id: string, level: 'view'|'update'|'manage'}>,
  }> {
    return new Observable(sub => {
      this.api.get(`/share/page/${this.node.id}/info`).subscribe(result => {
        sub.next(result.data);
        sub.complete();
      });
    });
  }

  setShareLevel(group, level) {
    this.api.post(`/share/page/${this.node.id}/share`, { user_id: group.id, level }).subscribe(result => {
      this.loadShareInfo().subscribe(data => {
        this.sharingInfo = data;
      });
    });
  }

  unsharePage(group) {
    this.api.post(`/share/page/${this.node.id}/revoke`, { user_id: group.id }).subscribe(result => {
      this.loadShareInfo().subscribe(data => {
        this.sharingInfo = data;
      });
    });
  }

  getShareLink(level) {
    this.api.get(`/share/page/${this.node.id}/link/${level}`).subscribe(result => {
      this.generatedLink = result.data.link;
    });
  }
}
