import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { combineLatest } from 'rxjs/observable/combineLatest';
import { Subscription } from 'rxjs/Subscription';
import { AppService } from '../../../app.service';
import { SEARCH, SERVICES } from '../../../constants';
import { MessageTemplateModel } from '../../../models/message-template.model';
import { SorterModel } from '../../../models/sorter-model';
import { SearchService } from '../../../oneit/services/search.service';
import { UtilsService } from '../../../oneit/services/utils.service';
import { AdminPortalLayoutService } from '../admin-portal-layout/admin-portal-layout.service';
import { BaseComponent } from '../base/base.component';

@Component({
    selector: 'app-list-message-template',
    templateUrl: './list-message-template.component.html'
})
export class ListMessageTemplateComponent extends BaseComponent implements OnInit {

    subscriptions: Array<Subscription> = [];
    myTemplates: Array<MessageTemplateModel> = [];
    sharedTemplates: Array<MessageTemplateModel> = [];
    sortOptions: Array<SorterModel>;
    showLoader = false;
    processing = false;
    isGlobalHT = false;

    constructor(
        private router: Router,
        private activatedRoute: ActivatedRoute,
        private utilsService: UtilsService,
        private searchService: SearchService,
        private appService: AppService,
        private adminPortalLayoutService: AdminPortalLayoutService
    ) {
        super(utilsService);
    }

    ngOnInit(): void {
        this.subscriptions.push(this.activatedRoute.params
            .subscribe(
                (params: Params) => {
                    if ((params.global && params.global === 'global')) {
                        this.isGlobalHT = true;
                    }
                }
            ));

        this.sortOptions = [
            new SorterModel('Alphabetical (A-Z)', true),
            new SorterModel('Alphabetical (Z-A)', false)
        ];
        this.showLoader = true;

        if (this.adminPortalLayoutService.userData || this.isGlobalHT) {
            this.initComponent();
        } else {
            this.subscriptions.push(
                this.adminPortalLayoutService.userDataUpdated.first()
                    .subscribe(
                        () => this.initComponent()
                    )
            );
        }

    }

    initComponent(): void {
        const sharedMsgParams = {
            OnlyGlobalTemplate: true
        };

        if(this.isGlobalHT) {
            this.subscriptions.push(
                combineLatest(
                    this.appService.getSearchListing(SERVICES.MESSAGE_TEMPLATES, 'All', sharedMsgParams, [], SEARCH.MESSAGE_TEMPLATE)
                )
                    .subscribe(
                        (response: [Array<MessageTemplateModel>]) => {
                            this.sharedTemplates = response[0];
                            this.sortSpecificTemplate('sharedTemplates');
                            this.showLoader = false;
                        }
                    )
            );
        } else {

            const myMsgParams = {
                OnlyGlobalTemplate: false,
                HiringTeam: this.adminPortalLayoutService.getHiringTeamID().ObjectID
            };

            this.subscriptions.push(
                combineLatest(
                    this.appService.getSearchListing(SERVICES.MESSAGE_TEMPLATES, 'All', myMsgParams, [], SEARCH.MESSAGE_TEMPLATE),
                    this.appService.getSearchListing(SERVICES.MESSAGE_TEMPLATES, 'All', sharedMsgParams, [], SEARCH.MESSAGE_TEMPLATE)
                )
                    .subscribe(
                        (response: [Array<MessageTemplateModel>, Array<MessageTemplateModel>]) => {
                            this.myTemplates = response[0];
                            this.sharedTemplates = response[1];
    
                            this.sortSpecificTemplate('myTemplates');
                            this.sortSpecificTemplate('sharedTemplates');
    
                            this.showLoader = false;
                        }
                    )
            );
        }        
    }

    sortSpecificTemplate(arrayName: string): void {
        this[arrayName] = this.utilsService.sort(this[arrayName],
            ['TemplateName'], [this.sortOptions[0].ascending ? 1 : -1], false);
    }

    sortMessageTemplates($event): void {

        if (!$event) {
            return;
        }

        this.showLoader = true;
        this.myTemplates = this.utilsService.sort(this.myTemplates,
            ['TemplateName'], [$event.ascending ? 1 : -1], false);
        this.sharedTemplates = this.utilsService.sort(this.sharedTemplates,
            ['TemplateName'], [$event.ascending ? 1 : -1], false);
        this.showLoader = false;
    }

    onRowSelect(data: MessageTemplateModel): void {
        this.router.navigate([this.isGlobalHT ? '/edit-message-template/global' : '/admin/edit-message-template', data.ObjectID]);
    }

    onNewTemplate(): void {
        this.router.navigate([this.isGlobalHT ? '/edit-message-template/global' : '/admin/edit-message-template']);
    }
}
