import { Component, OnInit, Output, EventEmitter, ViewEncapsulation, Input, ElementRef, ViewChild } from '@angular/core';
import { Profile } from './profile.model';
import { IScreenEditor } from '../screen-editor';
import { ProfileScreenComponent } from './profile-screen/profile-screen.component';

@Component({
  selector: 'profile-manager',
  templateUrl: './profile-manager.component.html',
  styleUrls: ['./profile-manager.component.css']
})
export class ProfileEditor implements OnInit {

  @Output() onDiscard : EventEmitter<string>  = new EventEmitter<string>();
  @Output() onAddNew : EventEmitter<Profile>  = new EventEmitter<Profile>();
  @Output() onSave : EventEmitter<Profile>  = new EventEmitter<Profile>();
  
  @Input() editorId : string;
  @Input()  editMode : string = 'V';
  @Input()  profileData : Profile;
  
  @ViewChild('editScreen') editScreen: ProfileScreenComponent;
  public editForm;
  
  oldProfile : Profile ;

  constructor() { }

  ngOnInit() {
  }
  
  ngAfterViewChecked(): void {
      if( this.editMode == 'E' ) {
          this.editForm = this.editScreen.userProfieForm;
      }
  }
  
  edit() {
      this.oldProfile = this.simpleClone( this.profileData );
      this.editMode = 'E';
      localStorage.setItem('editorId', this.editorId );
  }
  
  save(){
      console.log('save', this.profileData);

      this.onSave.emit(this.profileData);
      console.log('save...');
      localStorage.removeItem('editorId');
      this.editMode = 'V';
  }
  
  cancel(){
      console.log('cancel', this.profileData.birthDate, this.oldProfile.birthDate);
      this.profileData = this.oldProfile;
      localStorage.removeItem('editorId');

      this.editMode = 'V';
  }
  
  
  simpleClone(obj: any) {
      return Object.assign({}, obj);
    }
  
}
