import {Component, ViewChild, OnInit, Input, Output, ElementRef}     from '@angular/core';
import {ViewEncapsulation, EventEmitter}                 from '@angular/core';
import {SimpleChanges, OnChanges}                        from '@angular/core';
import {FormGroup, FormArray, FormBuilder, Validators}   from '@angular/forms';
import {ActivatedRoute, Router}                          from '@angular/router';
import {Subject}                                         from 'rxjs';
import {DataTableDirective}                              from 'angular-datatables';

import {EnvProperties}                                   from '../../openaireLibrary/utils/properties/env-properties';
import {SubscribeService}                                from '../../openaireLibrary/utils/subscribe/subscribe.service';
import {RouterHelper}                                    from '../../openaireLibrary/utils/routerHelper.class';

import {ErrorCodes}                                      from '../../openaireLibrary/utils/properties/errorCodes';
import {SearchUtilsClass}                                from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';

import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {HelperFunctions} from "../../openaireLibrary/utils/HelperFunctions.class";
import {Title} from '@angular/platform-browser';

@Component({
    selector: 'manage-subscribers',
    templateUrl: './manage-subscribers.component.html',
    styles: [`
      #dpTable_info, #dpTable_paginate,  #dpTable_length,  #dpTable_filter{
        display: none;
      }
    `],
    encapsulation: ViewEncapsulation.None // this used in order styles to work
})

export class ManageSubscribersComponent implements OnInit {
    public routerHelper:RouterHelper = new RouterHelper();

    private errorCodes: ErrorCodes;

    @Output() commmunitySubscribersChanged = new EventEmitter();
    public communitySubscribers = [];
    public subscribersSearchUtils: SearchUtilsClass = new SearchUtilsClass();

    public sub: any; public subResults: any; subRemove: any;
    public properties: EnvProperties;

    public disableForms: boolean = false;

    dtOptions: DataTables.Settings = {};
    showTable = false; filteringAdded = false;
    @ViewChild(DataTableDirective) datatableElement: DataTableDirective;
    dtTrigger: Subject<any> = new Subject(); //necessary

    public rowsOnPage:number = 10;

    public queryParameters: string = "";

    public query = '';
    public selectedSubscribersEmail=[];
    public elementRef;

    public subscribers:string[];
    private triggered: boolean = false;

    private selectedSubscriberEmail: any;

    public communityId = null;

    @ViewChild('AlertModalDeleteSubscriber') alertModalDeleteSubscriber;

    constructor (private element: ElementRef,
                 private route: ActivatedRoute,
                 private title: Title,
                 private _router: Router,
                 public _fb: FormBuilder,
                 private _subscribeService: SubscribeService) {

        this.errorCodes = new ErrorCodes();
        this.subscribersSearchUtils.status = this.errorCodes.LOADING;
    }

    ngOnInit() {
        this.route.data.subscribe((data: { envSpecific: EnvProperties }) => {
        this.properties = data.envSpecific;
        this.route.queryParams.subscribe(

            communityId => {
                HelperFunctions.scroll();

                this.communityId = communityId['communityId'];
                this.title.setTitle('Administration Dashboard | Subscribers');
                if (this.communityId != null && this.communityId != '') {
                    this._getCommunitySubscribers();
                }
            });
    });

        this.dtOptions = {
            "pageLength": this.rowsOnPage,
            "language": {
                "search": "",
                "searchPlaceholder": "Search subscribers..."
            }
        };

        this.subscribersSearchUtils.keyword = "";
    }

    public ngOnDestroy() {
        if(this.sub){
          this.sub.unsubscribe();
        }
        if(this.subResults) {
          this.subResults.unsubscribe();
        }
        if(this.subRemove) {
          this.subRemove.unsubscribe();
        }

        $.fn['dataTable'].ext.search.pop();
    }

    rerender(): void {
        this.datatableElement.dtInstance.then((dtInstance: DataTables.Api) => {
            // Destroy the table first
            dtInstance.destroy();

            // Call the dtTrigger to rerender again
            this.dtTrigger.next();
        });
    }

    ngAfterViewInit(): void {
        $.fn['dataTable'].ext.search.push((settings, data, dataIndex) => {

            if (this.filterData(data, this.subscribersSearchUtils.keyword)) {
                return true;
            }
                return false;
        });

        //console.info("ngAfterViewInit");
    }

    filterData(row: any, query: string) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        let returnValue: boolean = false;

        if(query) {
            for(var i = 0; i < 2; i++) {
                var r= this.filterQuery(row[i], query);
                if(r) {
                    returnValue = true;
                    break;
                }
            }

            if(!returnValue) {
                return false;
            }
        }
        return true;
      }
    }

    filterQuery(data, query){
        if(data.toLowerCase().indexOf(query.toLowerCase()) > -1) {
            return true;
        } else {
            return false;
        }
    }

    /*
    Trigger a table draw in order to get the initial filtering
    */
    triggerInitialLoad(){
        this.triggered = true;
        //console.info("triggerInitialLoad");
        setTimeout(function() {
            var table = (<any>$('#dpTable')).DataTable();
            table.page( 0  ).draw( false );
        }, 500);
        this.dtTrigger.next();
    }

    public goTo(page:number = 1) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this.subscribersSearchUtils.page=page;

        var table = $('#dpTable').DataTable();
        table.page( page - 1  ).draw( false );

        var info = table.page.info();
        this.subscribersSearchUtils.totalResults = info.recordsDisplay;
      }
    }

    totalPages(): number {
        let totalPages:any = this.subscribersSearchUtils.totalResults/(this.rowsOnPage);
        if(!(Number.isInteger(totalPages))) {
            totalPages = (parseInt(totalPages, 10) + 1);
        }
        return totalPages;
    }

    public removeSubscriber(email:string) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this.selectedSubscriberEmail = email;
        this.alertModalDeleteSubscriber.cancelButton = true;
        this.alertModalDeleteSubscriber.okButton = true;
        this.alertModalDeleteSubscriber.alertTitle = "Remove subscriber?";

        this.alertModalDeleteSubscriber.message = "Subscriber with email ";
            if (email) {
                this.alertModalDeleteSubscriber.message += " '"+email+"' ";
            }

        this.alertModalDeleteSubscriber.message += "will be removed from your community. Are you sure?";
        this.alertModalDeleteSubscriber.okButtonText = "Yes";
        this.alertModalDeleteSubscriber.open();
      }
    }

    public confirmedDeleteSubscriber() {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this.subRemove = this._subscribeService.unSubscribeToCommunityByEmail(this.properties, this.communityId, this.selectedSubscriberEmail).subscribe(
            result => {
                this.communitySubscribers = result;
            },
            err => {
                console.log(err);
            },
            () => {
                this.subscribersSearchUtils.totalResults--;
                this.subscribersSearchUtils.page=1;

                this.rerender();
            }
        )
      }
    }

    public _getCommunitySubscribers(){
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this.subscribersSearchUtils.status = this.errorCodes.LOADING;
        this.disableForms = true;
        this.communitySubscribers = [];
        this.subscribersSearchUtils.totalResults = 0;
        this.subscribersSearchUtils.page=1;
        this.subscribersSearchUtils.keyword = "";

        this.subResults = this._subscribeService.getCommunitySubscribers(this.properties, this.communityId).subscribe(

            res => {
                //console.info("search Subscribers [total communitySubscribers:"+res.subscribers.length+"]");
                this.communitySubscribers = res;

                this.subscribersSearchUtils.totalResults = res.subscribers.length;
                this.subscribersSearchUtils.status = this.errorCodes.DONE;

                this.disableForms = false;
                if(!this.triggered) {
                    this.triggerInitialLoad();
                } else {
                    var table = $('#dpTable').DataTable();
                    table.clear();

                this.rerender();
                }

                this.commmunitySubscribersChanged.emit({
                    value: this.communitySubscribers,
                });
            },
            err => {
                console.log(err);
                //TODO check erros (service not available, bad request)

                if(err.status == '404') {
                    this.subscribersSearchUtils.status = this.errorCodes.NOT_FOUND;
                } else if(err.status == '500') {
                    this.subscribersSearchUtils.status = this.errorCodes.ERROR;
                } else {
                    this.subscribersSearchUtils.status = this.errorCodes.NOT_AVAILABLE;
                }

                this.disableForms = false;
                if(!this.triggered) {
                    this.triggerInitialLoad();
                } else {
                    var table = $('#dpTable').DataTable();
                    table.clear();

                    this.rerender();
                }
            }
        );
      }
    }
}
