import {Component} from '@angular/core';
import {Router} from '@angular/router';
import {AppConfig} from '../config/app.config';
import {HttpClient} from '@angular/common/http';
import {AlertService} from '../core/alert.service';

/**
 * @title Table with filtering
 */
@Component({
    templateUrl: 'password.component.html',
    styleUrls: ['password.component.scss']
})

export class PasswordComponent {
    currentUser: any;
    person: any;

    constructor(private router: Router,
                private http: HttpClient,
                private alertService: AlertService) {
        this.currentUser = JSON.parse(sessionStorage.getItem(AppConfig.relativeURL + 'currentUser'));
        this.person = {};
    }

    updatePassword() {
        this.updateCustomerPassword(this.currentUser).subscribe(
            data => {
                this.alertService.success('Password has been changed successfully!');
            },
            error => {
                if (typeof error === 'string') {
                    this.alertService.error(error);
                } else {
                    this.alertService.error('Error');
                }
            });
    }

    private updateCustomerPassword(currentUser) {
        return this.http.post<any>(AppConfig.endpointURL() + AppConfig.endpoints.updateCustomerPassword + currentUser.sessionID, {
            'userName': currentUser.userName,
            'oldpassword': this.person.oldPassword,
            'newpassword': this.person.newPassword,
        }, {headers: {'Content-Type': 'text/plain'}}).map(data => {
            if (data && data.errorTable) {
                throw data.errorTable[0].msg;
            } else {
                return data;
            }
        });
    }

}
