import { Component, OnInit } from '@angular/core';
import { NavController } from '@ionic/angular';
import * as Parse from 'parse';

@Component({
  selector: 'app-edit-info',
  templateUrl: './edit-info.component.html',
  styleUrls: ['./edit-info.component.scss']
})
export class EditInfoComponent implements OnInit {

  userInfo: any = {
    name: '',
    mobile: '',
    gender: '',
    birthday: ''
  };
  currentUser: Parse.User | undefined;
  lcmUser: Parse.Object<Parse.Attributes> | undefined;

  constructor(private navController: NavController) {}

  ngOnInit() {
    this.currentUser = Parse.User.current();
    if (this.currentUser) {
      let json = this.currentUser.toJSON();
      for (const key in json) {
        if (this.userInfo.hasOwnProperty(key)) {
          this.userInfo[key] = json[key];
        }
      }
    }

    if (this.currentUser) {
      const LcmUser = Parse.Object.extend('LcmUser');
      const query = new Parse.Query(LcmUser);
      query.equalTo('objectId', this.currentUser.id);
      query.first().then((lcmUser) => {
        if (lcmUser) {
          this.lcmUser = lcmUser;
          console.log('Found corresponding LcmUser data: ', this.lcmUser);
        } else {
          console.log('LcmUser data not found');
        }
      }).catch((error) => {
        console.error('Error querying LcmUser data: ', error);
      });
    }
  }

  save() {
    if (this.lcmUser) {
      for (const key in this.userInfo) {
        if (this.userInfo.hasOwnProperty(key)) {
          this.lcmUser.set(key, this.userInfo[key]);
        }
      }
      this.lcmUser.save().then(() => {
        console.log('Successfully saved to LcmUser table');
        this.navController.back();
      }).catch((error) => {
        console.error('Error saving to LcmUser table: ', error);
      });
    }
  }

  cancel() {
    this.navController.back();
  }

}
