import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {CommunityDTO, LocalUserDTO} from "../../models/enea/LocalUserDTO";
import {UserService} from "../../services/user.service";

import {TranslateService} from "@ngx-translate/core";
import {UtilsService} from "../../services/utils.service";
import {ValidationService} from "../../services/validation.service";
import {NgForm} from "@angular/forms";
import  {AppService} from "src/app/services/app.service";
import {User} from 'src/app/models/User';

@Component({
    selector: 'app-changepassword',
    templateUrl: './changepassword.component.html',
    styleUrls: ['./changepassword.component.css']
})
export class ChangepasswordComponent implements OnInit {
    loading: boolean = false;
    model: LocalUserDTO = {};
    errorMessages: any[] = [];
    
    constructor(
        private userService: UserService,
        private translateService: TranslateService,
        private utils: UtilsService,
        public validation: ValidationService,
        private app: AppService
    ) { }

    ngOnInit(): void {
         	}
        
    update() {
        this.translateService.get(['CHANGEPASSWORD.SUCCESS','CHANGEPASSWORD.OLDPASSWORD', 'CHANGEPASSWORD.PASSWORD', 'CHANGEPASSWORD.REPEAT_PASSWORD']).subscribe(o => {
            this.errorMessages = this.validation.validate( [
				{
   					value: this.model.oldpassword,
    				validators: [ValidationService.notEmpty],
    				name: o['CHANGEPASSWORD.OLDPASSWORD']
				},
                {
                    value: this.model.password,
                    validators: [ValidationService.securePassword],
                    name: o['CHANGEPASSWORD.PASSWORD']
                },
                {
                    value: this.model.passwordRepeat,
                    validators: [ValidationService.notEmpty, ValidationService.equalTo(this.model.password)],
                    name: o['CHANGEPASSWORD.REPEAT_PASSWORD']
                }
            ]);

            if (!this.errorMessages || this.errorMessages.length < 1) {
                this.loading = true;
                this.userService.updatePassword(this.model).subscribe(response => {
                	this.utils.showInfoMessageTrans(response);
                    this.loading = false;
                    if (response || response.success) {
                        this.utils.showInfoMessageTrans("CHANGEPASSWORD.SUCCESS");
                    }
                    else {
                        this.utils.showWarnMessage(response.message);
                    }
                }, error => {this.loading = false;})
            }
        });
    }
}

