import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {CommunityDTO, LocalUserDTO} from "../../models/enea/LocalUserDTO";
import {UserService} from "../../services/user.service";
import {MenuItem} from "primeng/api";
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';
import { Router } from '@angular/router';

@Component({
    selector: 'app-update',
    templateUrl: './update.component.html',
    styleUrls: ['./update.component.css']
})
export class UpdateComponent implements OnInit {
    static getListOfCommunieites(): import("../../models/Community").Community[] {
        throw new Error('Method not implemented.');
    }
    loading: boolean = false;
    model: LocalUserDTO = {};
    communities: MenuItem [] = [];
    errorMessages: any[] = [];
    
    user: User = this.app.user;

    constructor(
        private userService: UserService,
        private translateService: TranslateService,
        private utils: UtilsService,
        public validation: ValidationService,
        private app: AppService,
        private router: Router
    ) { }

    ngOnInit(): void {
        this.initCommunitiesLoader();
        if (this.user){
        	this.model = {
                    usercommunities: this.user.usercommunities,
                    email: this.user.username,
                    name: this.user.name,
                    surname: this.user.surname,
                    organization: this.user.organization,
                    token: this.user.token,
                    password: "",
                    passwordRepeat: ""
                	};
        }else {
        this.model = {
            usercommunities: [],
            email: "",
            name: "",
            surname: "",
            password: "",
            passwordRepeat: ""
        	};
    	}
    }
    initCommunitiesLoader() {
        this.translateService.get("LABEL.LOADING").subscribe(o => {
            this.communities = [
                {
                    icon: "pi pi-spin pi-spinner",
                    label: o
                }
            ]
        });
    }

    getListOfCommunieites(): CommunityDTO[] {
       
        this.getCommunities();
        return this.communities as CommunityDTO[] ;
    }

    getCommunities () {
        this.initCommunitiesLoader();
        this.userService.getCommunities().subscribe((items: CommunityDTO[]) => this.communities = items.map(o => {
            console.info(o);
            return {
                id: o.communityid,
                label: o.description,
                state: {
                    selectedItem: o
                },
                command: (value: any) => {
                    if (this.model && !this.model.usercommunities)
                        this.model!.usercommunities = [value.item.state.selectedItem];
                    else if (this.model && this.model.usercommunities && !this.model.usercommunities.some(o => o.communityid == value.item.state.selectedItem.communityid )) {
                        this.model!.usercommunities?.push(value.item.state.selectedItem);
                    }
                    else {
                        this.utils.showErrorMessageTrans("UPDATE.COMMUNITY_SELECTED");
                    }
                }
            }
        }));
    }

    update() {
        this.translateService.get(['UPDATE.EMAIL','UDPATE.NAME', 'UPDATE.SURNAME', 'UPDATE.PASSWORD', 'UPDATE.REPEAT_PASSWORD']).subscribe(o => {
            this.errorMessages = this.validation.validate( [
                {
                    value: this.model.email,
                    validators: [ValidationService.email],
                    name: o['UPDATE.EMAIL']
                },
                {
                    value: this.model.name,
                    validators: [ValidationService.notEmpty],
                    name: o['UPDATE.NAME']
                },
                {
                    value: this.model.surname,
                    validators: [ValidationService.notEmpty],
                    name: o['UPDATE.SURNAME']
                }
            /*    {
                    value: this.model.password,
                    validators: [ValidationService.securePassword],
                    name: o['UPDATE.PASSWORD']
                },
                {
                    value: this.model.passwordRepeat,
                    validators: [ValidationService.notEmpty, ValidationService.equalTo(this.model.password)],
                    name: o['UPDATE.REPEAT_PASSWORD']
                }*/
            ]);

            if (!this.errorMessages || this.errorMessages.length < 1) {
                this.loading = true;
                this.userService.update(this.model).subscribe(response => {
                    this.loading = false;
                    if (response.success || response === true) {
                        this.utils.showInfoMessageTrans("UPDATE.SUCCESS");
                        this.model = {usercommunities: []};
                        this.router.navigateByUrl("/");
                        this.user.name = this.model.name!;
                        this.user.organization = this.model.organization!;
                        this.user.username = this.model.email!;
                        this.user.usercommunities = this.model.usercommunities!;
                        this.user.surname = this.model.surname!;
                        
                        this.user.newUser = false;
                    }
                    else {
                        this.utils.showWarnMessage(response.message);
                    }
                }, error => {this.loading = false;})
            }
        });
    }
}

