import {Component, OnInit} 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 {takeWhile} from 'rxjs/operators';
import {Authorization} from 'src/app/models/Authorization';
import {AuthService} from "../../services/auth.service";

@Component({
    selector: 'app-register',
    templateUrl: './register.component.html',
    styleUrls: ['./register.component.css']
})
export class RegisterComponent implements OnInit {
    loading: boolean = false;
    model: LocalUserDTO = {};
    communities: MenuItem [] = [];
    errorMessages: any[] = [];
    user: any;
    alive: boolean = true;

    constructor(
        private userService: UserService,
        private authService: AuthService,
        private translateService: TranslateService,
        private utils: UtilsService,
        public validation: ValidationService
    ) {
    }

    ngOnInit(): void {
        this.initCommunitiesLoader();

        this.authService.onAuthChange()
            .pipe(takeWhile(() => this.alive))
            .subscribe((authorization: Authorization) => {
                if (authorization) {
                    this.user = authorization.user;
                }
            });


        this.model = {
            usercommunities: this.user.usercommunities ? this.user.usercommunities : [],
            email: this.user.username ? this.user.username : "",
            name: this.user.name ? this.user.name : "",
            surname: this.user.surname ? this.user.surname : "",
            organization: this.user.organization ? this.user.organization : "",
            password: "",
            passwordRepeat: ""
        };
    }

    initCommunitiesLoader() {

        this.translateService.get("LABEL.LOADING").subscribe(o => {
            this.communities = [
                {
                    icon: "pi pi-spin pi-spinner",
                    label: o
                }
            ]
        });
    }

    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("REGISTER.COMMUNITY_SELECTED");
                    }
                }
            }
        }));
    }

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

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

