import { Component, OnDestroy, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { ConfirmationService } from 'primeng/api';
import { Subscription } from 'rxjs/Subscription';
import { SaveService } from '../../../oneit/services/save.service';
import { UtilsService } from '../../../oneit/services/utils.service';
import { ViewCareerUserService } from './view-career-user.service';


@Component({
    selector: 'app-view-user',
    templateUrl: './view-career-user.component.html'
})
export class ViewCareerUserComponent implements OnInit, OnDestroy {
    
    subscriptions: Array<Subscription> = [];
    @ViewChild('form') form: NgForm;
    
    successfulInvitesCols = [
        { field: 'Email', header: 'Email', width: '31%', noSort: true, noFilter: true},
        { field: 'Name', header: 'Name', width: '31%', noSort: true, noFilter: true},
        { field: 'JoinedDate', header: 'Joined Date', width: '31%', noSort: true, noFilter: true},
        { field: '', header: '', width: '7%', noSort: true, noFilter: true}
    ];

    bosCols = [
        { field: 'Field', header: 'Field', width: '25%', noSort: true, noFilter: true},
        { field: 'ChangeType', header: 'Change Type', width: '25%', noSort: true, noFilter: true},
        { field: 'Old', header: 'Old', width: '25%', noSort: true, noFilter: true},
        { field: 'New', header: 'New', width: '25%', noSort: true, noFilter: true}
    ];

    careerUser: any;
    showLoader: boolean = false;
    invitees: any[] = [];
    
    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private utilsService: UtilsService,
        private saveService: SaveService,
        private confirmationService: ConfirmationService,
        private viewUserService: ViewCareerUserService
    ){
        
    }

    ngOnInit() {
        this.subscriptions.push(this.activatedRoute.params
            .subscribe(
                (params: Params) => {
                    this.showLoader = true;
                    if (params.id && params.id !== '0') {
                        this.showLoader = false;
                        this.getCareerUserByID(params.id);
                    }
                }
            ));
    }

    getCareerUserByID(id: string) {
        
        this.showLoader     =   true;
        let assocs          =   ['Candidate', 'Candidate.User', 'Candidate.ReferredBy', 'Candidate.Invitees', 'Candidate.Invitees.User'];
        
        this.subscriptions.push(this.viewUserService.getCareerUserByID(id, assocs)
            .subscribe(
                data => {
                    this.careerUser = data;
                    this.invitees = [];

                    if (this.careerUser.Candidate && this.careerUser.Candidate.Invitees) {
                        for (let invitee of this.careerUser.Candidate.Invitees) {
                            this.invitees.push({Email: invitee.User.Email, Name: invitee.User.Name, JoinedDate: invitee.ObjectCreated, IsNew: false});
                        }
                    }

                    this.careerUser.Candidate.NewInvitationEmails = [];
                    this.showLoader = false;
                },
                error => {
                    this.showLoader = false;
                    this.utilsService.handleError(error);
                }
            )
        );
    }

    saveUser(reload: boolean) {
        this.utilsService.clearErrorMessages();
        if (this.form.invalid) {
            this.utilsService.showAllErrorMessages();
        } else {
            this.showLoader = true;
            let updatedObjs = {};
            this.careerUser.Candidate.NewInvitationEmails = [];

            for (let invitee of this.invitees) {
                if (invitee.IsNew) {
                    this.careerUser.Candidate.NewInvitationEmails.push(invitee.Email);
                }
            }
            
            this.utilsService.addObjsToJSONByObjectID(updatedObjs, [this.careerUser.Candidate]);

            this.subscriptions.push(this.saveService.saveObjectsWithDefaultSvc({}, updatedObjs, {})
                .subscribe(
                    data => {
                        this.utilsService.handleSuccess();
                        if (reload) {
                            let idToNavigate = this.careerUser.ObjectID;
                            this.getCareerUserByID(idToNavigate);
                        }
                        else {
                            this.router.navigate(["/my-career/my-career-users"]);
                        }
                        this.showLoader = false;
                    },
                    error => {
                        this.showLoader = false;
                        this.utilsService.handleError(error);
                    }
                )
            );
        }
    }

    removeReferredBy() {
        this.showLoader = true;
        const params = {
            CareerProfile: this.careerUser
        };
        
        this.utilsService.processObjects('RemoveReferredBy', params).subscribe(
            () => {
                this.getCareerUserByID(this.careerUser.ObjectID);
                this.showLoader = false;
            },
            err => {
                this.utilsService.handleError(err);
                this.showLoader = false;
            }
        );
    }
    
    addSuccessfulInvites() {
        this.invitees.push({Email: '', IsNew: true});
    }

    deleteRow(invitee: any) {
        this.utilsService.clearErrorMessages();
        
        this.confirmationService.confirm({
            message: 'Are you sure you want to delete this record?',
            header: 'Delete Confirmation',
            icon: 'fa fa-trash',
            accept: () => {
                const index = this.invitees.indexOf(invitee);
                this.invitees.splice(index, 1);
            }
        });
    }
    
    ngOnDestroy(){
        this.utilsService.unsubscribeSubscriptions(this.subscriptions);
    }
}