import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';

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

import { ILanguage, ILanguages } from '../core/shared/language/language.model';
import { LanguageService } from '../core/shared/language/language.service';

import { BaseComponent } from '../core/components/base.component';

@Component({
    selector: 'knk-my-account',
    templateUrl: './myaccount.component.html',
    styleUrls: ['./myaccount.component.scss']
})
export class MyAccountComponent extends BaseComponent implements OnInit {
    user: IUser;
    accounts: IAccount[];
    editUser: IUser;
    edit = false;
    languages: ILanguage[];
    phoneFull: string;
    registrationError: { id: number, msg: string } = null;

    constructor(protected userService: UserService,
        route: ActivatedRoute,
        private languageService: LanguageService) {
            super(userService, route);
    }
    ngOnInit(): void {
        super.ngOnInit();
        this.userService.loadUser().subscribe(userAccounts => {
            this.user = userAccounts.user;
            this.accounts = userAccounts.accounts;
            this.editUser = Object.assign({}, this.user);
            this.phoneFull = this.editUser.phonePrefix + this.editUser.phone;
            // this.loaderSubscription.unsubscribe();
        });
        this.languageService.Languages.subscribe((languages: ILanguages) => {
            this.languages = languages.items;
            languages.items.forEach(function(lang: ILanguage, key: number): void {
                if (lang.languageCode === this.lang) {
                    this.user.languageId = lang.languageId;
                    return;
                }
            }, this);
        });
    }
    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);
            },
            (err) => {
                this.registrationError = err.error;
            }
        );
    }
    parsePhone(): void {
        if (this.phoneFull) {
            let p: string = this.phoneFull.replace(/\s+|-|\+/g, '');
            if (p.length >= 7) {
                this.editUser.phonePrefix = p.substr(0, p.length - 7);
                this.editUser.phone = p.substr(p.length - 7);
            }
        }
    }
}
