import { Component, OnInit } from '@angular/core';
import * as Parse from "parse";
@Component({
  selector: 'app-contact-list',
  templateUrl: './contact-list.page.html',
  styleUrls: ['./contact-list.page.scss'],
})
export class ContactListPage implements OnInit {
  searchName: string = '';
  contactList: Array<Parse.Object> = [];
  segment:string = "me";
  ngOnInit() {
    this.loadContact();
  }

  usernameInput:string = ""
  async checkIfExists(toUser:Parse.Object){
    let query = new Parse.Query("Contact");
    query.equalTo("from",Parse.User.current()?.toPointer())
    query.equalTo("to",toUser.toPointer())
    return await query.first();
  }
  async addContact(){
    if(this.usernameInput){
      let query = new Parse.Query("_User");
      query.equalTo("username",this.usernameInput);
      let user = await query.first()
      if(user?.id){
        let exists = await this.checkIfExists(user)
        if(exists?.id) return
        let Contact = Parse.Object.extend("Contact");
        let contact = new Contact()
        contact.set("from",Parse.User.current()?.toPointer())
        contact.set("to",user.toPointer())
        await contact.save();
        this.loadContact();
      }else{
        // 提示找不到用户
      }
    }
  }
  charGroupIndex:any = {}
  loadContact() {
    const Contact = Parse.Object.extend('Contact');
    const query = new Parse.Query(Contact);
    query.include("to")
    query.ascending('firstChar');
    if(this.segment=="me"){
      if(!Parse.User.current()?.id) return
      query.equalTo("from",Parse.User.current()?.id)
    }

    if (this.searchName) {
      query.contains('name', this.searchName);
    }

    query.find().then((results) => {
      this.contactList = results;
      this.contactList.forEach((contact,index)=>{
        if(this.charGroupIndex[contact.get("firstChar")] == undefined){
          this.charGroupIndex[contact.get("firstChar")] = index
        }
      })
    }, (error) => {
      console.error('Error while fetching contacts', error);
    });
  }

  search() {
    this.loadContact();
  }

}
