import { Component, OnDestroy, OnInit } from '@angular/core';

import { Subscription } from 'rxjs/Subscription';

import { IAccount, IUser, LoaderService, UserService } from '../core/shared';

@Component({
    selector: 'knk-my-account',
    templateUrl: './myaccount.component.html',
    styleUrls: ['./myaccount.component.scss']
})
export class MyAccountComponent implements OnInit, OnDestroy {
    user: IUser;
    accounts: IAccount[];
    editUser: IUser;
    edit = false;
    languages: { id: string, value: string }[] = [
        { value: 'English', id: 'en' },
        { value: 'Español', id: 'es' },
        { value: '中文', id: 'zh' },
        { value: 'Português', id: 'pt' },
        { value: '日本語', id: 'ja' },
        { value: 'Русский', id: 'ru' }
    ];
    private loaderSubscription: Subscription;
    constructor(private userService: UserService, private loaderService: LoaderService) {
        this.loaderSubscription = this.loaderService.subscribeLoader(this);
    }
    ngOnInit(): void {
        this.userService.loadUser().subscribe(userAccounts => {
            this.user = userAccounts.user;
            this.accounts = userAccounts.accounts;
            this.editUser = Object.assign({}, this.user);
            this.loaderSubscription.unsubscribe();
        });
    }
    toggleEditMode(isEditMode: boolean = false): void {
        this.edit = isEditMode;
        if (this.edit) {
            this.editUser = Object.assign({}, this.user);
        }

    }
    save(): void {
        this.userService.updateUser(this.editUser).subscribe(() => {
            Object.assign(this.user, this.editUser);
            this.toggleEditMode(false);
        });
    }
    ngOnDestroy(): void {
        this.loaderSubscription.unsubscribe();
    }
}
