import { CommonModule, DatePipe } from '@angular/common';
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NavComponent } from '../../../app/components/nav/nav.component';
import { ionicStandaloneModules } from '../../ionic-standalone.modules';
import * as Parse from 'parse';
import { InfiniteScrollCustomEvent } from '@ionic/angular';

@Component({
  selector: 'app-call-log',
  templateUrl: './call-log.component.html',
  styleUrls: ['./call-log.component.scss'],
  standalone: true,
  imports: [...ionicStandaloneModules, NavComponent, CommonModule],
  providers: [DatePipe],
})
export class CallLogComponent implements OnInit {
  list: Array<any> = [];
  user:Parse.User = Parse.User.current()
  constructor(private router: Router) {}

  ngOnInit() {
    this.getLiveLog();
  }
  async getLiveLog() {
    let profile = JSON.parse(localStorage.getItem('profile') || '{}');
    let queryParams: any = {
      where: {
        $or: [
          {
            user: Parse.User.current()?.id,
          },
          {
            profile: profile?.objectId,
          },
        ],
      },
    };
    let query = Parse.Query.fromJSON('LiveLog', queryParams);
    query.notEqualTo('isDeleted', true);
    query.limit(20);
    query.skip(this.list.length);
    query.include('profile.user');
    query.descending('createdAt');
    let log = await query.find();
    this.list.push(...log)
    return log
  }

  toUrl(id: string) {
    this.router.navigate(['live/call-log/detail/' + id]);
  }

  async onIonInfinite(ev:any) {
    let result = await this.getLiveLog();
    if(result.length == 0) {
      (ev as InfiniteScrollCustomEvent).target.disabled = true;
    }
    setTimeout(() => {
      (ev as InfiniteScrollCustomEvent).target.complete();
    }, 500);
  }
}
