import { Component, OnInit, ViewChildren, QueryList} from '@angular/core';
import { Profile } from './profile-manager/profile.model';
import { ProfileEditor } from './profile-manager';
import { AppState } from '../ecm-store/reducers';
import { Store } from '@ngrx/store';
import { ProfileActions} from '../ecm-store/actions';
import { Observable } from 'rxjs/Observable';
import { ProfileInfoService } from './profile-info.service';


@Component({
  selector: 'user-profile',
  templateUrl: './user-profile.component.html',
  styleUrls: ['./user-profile.component.css'],
//  providers: [ProfileInfoService]
})
export class UserProfileComponent implements OnInit {
    
  @ViewChildren(ProfileEditor) profileEditors: QueryList<ProfileEditor>
  profileData;
  addressdata;
  
  constructor(private store: Store<AppState>,private profileActions: ProfileActions,){}
  
  ngOnInit() {
      
      localStorage.removeItem('editorId');
      this.store.dispatch(this.profileActions.loadProfile());
      this.loadUser();
      //this.onSaveClick();
     // console.log("The user info is ",this.onSaveClick());
  }

//  onSaveClick(profileData: Profile)
  onSaveClick(profileData: Profile)
   {
      console.log('On Save Click ', this.profileData, profileData);
      profileData.userName = profileData.firstName + " " + profileData.lastName;
      console.log('On Save Click ', this.profileData, profileData);
      this.profileData = profileData;
      //TODO Call POST service (userInfo)
      this.store.dispatch(this.profileActions.updateUserInfo(profileData));
  }
  

  onDiscard(editorId: string)
  {
      console.log('On Discard Click ', editorId);
      this.profileEditors.forEach(profileEditor => {
          if( editorId == profileEditor.editorId ) {
              console.log(profileEditor);
              profileEditor.cancel();
          }
      });
      //TODO Call POST service (profile)
  }
  
   loadUser() {
       this.store.select('profileInfo').subscribe( profileInfo => { 
           console.log('loadUser profileInfo >> ', profileInfo);
           this.profileData = profileInfo;
       });
    }
  
}
