import {  OnInit } from '@angular/core';
import { Component } from '@angular/core';
import { IonHeader, IonToolbar, IonTitle, IonContent, IonCard, IonCardContent, IonButton, IonCardHeader, IonCardTitle, IonCardSubtitle, ModalController, IonInput, IonItem, IonSegment, IonSegmentButton, IonLabel } from '@ionic/angular/standalone';
import { CloudUser } from 'src/lib/ncloud';

@Component({
  selector: 'app-modal-user-edit',
  templateUrl: './modal-user-edit.component.html',
  styleUrls: ['./modal-user-edit.component.scss'],
  standalone: true,
  imports: [IonHeader, IonToolbar, IonTitle, IonContent, 
    IonCard,IonCardContent,IonButton,IonCardHeader,IonCardTitle,IonCardSubtitle,
    IonInput,IonItem,
    IonSegment,IonSegmentButton,IonLabel
  ],
})
export class ModalUserEditComponent  implements OnInit {

  currentUser:CloudUser|undefined
  userData:any = {}
  userDataChange(key:string,ev:any){
    let value = ev?.detail?.value
    if(value){
      this.userData[key] = value
    }
  }
  constructor(private modalCtrl:ModalController) { 
    this.currentUser = new CloudUser();
    this.userData = this.currentUser.data;
  }

  ngOnInit() {}

  async save(){
    Object.keys(this.userData).forEach(key=>{
      if(key=="age"){
        this.userData[key] = Number(this.userData[key])
      }
    })

    this.currentUser?.set(this.userData)
    await this.currentUser?.save()
    this.modalCtrl.dismiss(this.currentUser,"confirm")
  }
  cancel(){
    this.modalCtrl.dismiss(null,"cancel")

  }
}

export async function openUserEditModal(modalCtrl:ModalController):Promise<CloudUser|null>{
  const modal = await modalCtrl.create({
    component: ModalUserEditComponent,
    breakpoints:[0.7,1.0],
    initialBreakpoint:0.7
  });
  modal.present();

  const { data, role } = await modal.onWillDismiss();

  if (role === 'confirm') {
    return data;
  }
  return null
}