import { Component, ViewChild, OnInit, ViewEncapsulation, Input, Output, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { Subject } from 'rxjs';
import { DataTableDirective } from 'angular-datatables';

import {ErrorCodes} from '../../../openaireLibrary/utils/properties/errorCodes';
import {SearchUtilsClass } from '../../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
import {EnvProperties} from '../../../openaireLibrary/utils/properties/env-properties';
import {ManageCommunityContentProvidersService} from '../../../services/manageContentProviders.service';
import {SearchCommunityDataprovidersService} from '../../../openaireLibrary/connect/contentProviders/searchDataproviders.service';
import {RouterHelper} from '../../../openaireLibrary/utils/routerHelper.class';
import {DOI, StringUtils} from '../../../openaireLibrary/utils/string-utils.class';

import {Session} from '../../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../../openaireLibrary/login/utils/guardHelper.class';
import {SelectionCriteria} from '../../../openaireLibrary/utils/entities/contentProvider';
import {CriteriaComponent} from './criteria/criteria.component';

@Component({
    selector: 'remove-content-providers',
    templateUrl: './remove-content-providers.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 RemoveContentProvidersComponent implements OnInit {
  public routerHelper:RouterHelper = new RouterHelper();

  private community: string = '';
  public communityUrl: string = "https://beta.explore.openaire.eu";

  private errorCodes: ErrorCodes;

  @Output() communityContentProvidersChanged  = new EventEmitter();
  public communityContentProviders = [];
  public communitySearchUtils:SearchUtilsClass = new SearchUtilsClass();

  public sub: any; public subResults: any; subRemove: any;
  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 selectedContentProviders=[] ;
  public elementRef;

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

  private selectedCommunityContentProvider: any;

  @ViewChild('AlertModalDeleteCommunity') alertModalDeleteCommunity;

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

    this.route.queryParams.subscribe(params => {
      if(params['communityId']) {
        this.community = params['communityId'];
        this.communityUrl = "https://beta."+this.community+".openaire.eu";

        this._getCommunityContentProviders();
      }
    });

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

    this.communitySearchUtils.keyword = "";
  }

  constructor(private route: ActivatedRoute, private _router: Router,
              private _manageCommunityContentProvidersService: ManageCommunityContentProvidersService,
              private _searchCommunityContentProvidersService: SearchCommunityDataprovidersService) {
    this.errorCodes = new ErrorCodes();
    this.communitySearchUtils.status = this.errorCodes.LOADING;
  }

  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.communitySearchUtils.keyword)) {
         return true;
       }
       return false;
     });

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

  public getCriteriaLabel(selectionCriteria: SelectionCriteria): string {
    if(selectionCriteria && selectionCriteria.criteria.length > 0) {
      return (selectionCriteria.criteria.length === 1)?'1 criterion':(selectionCriteria.criteria.length + ' criteria')
    } else {
      return 'no criteria';
    }
  }

  filterData(row: any, query: string) {
    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();
  }

  goTo(page:number = 1){
      this.communitySearchUtils.page=page;

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

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

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

  public confirmedDeleteContentProvider(data : any) {
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      this.subRemove = this._manageCommunityContentProvidersService.removeContentProvider(this.properties, this.community, this.selectedCommunityContentProvider.id).subscribe(
        data => {
          //console.info(data);
        },
        err => {
          console.log(err);
        },
        () => {
          let index = this.communityContentProviders.indexOf(this.selectedCommunityContentProvider);
          this.communityContentProviders.splice(index, 1);

          this.communitySearchUtils.totalResults--;
          this.communitySearchUtils.page=1;

          this.rerender();
        }
      )
    }
  }

  public removeContentProvider(communityContentProvider: any) {
    if(!Session.isLoggedIn()){
      this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
    } else {
      this.selectedCommunityContentProvider = communityContentProvider;
      this.alertModalDeleteCommunity.cancelButton = true;
      this.alertModalDeleteCommunity.okButton = true;
      this.alertModalDeleteCommunity.alertTitle = "Remove content provider?";
      let title = "";
      if(communityContentProvider.name) {
        title = communityContentProvider.name;
      }
      if(communityContentProvider.name && communityContentProvider.acronym) {
        title += " (";
      }
      if(communityContentProvider.acronym) {
        title += communityContentProvider.acronym;
      }
      if(communityContentProvider.name && communityContentProvider.acronym) {
        title += ") ";
      }
      this.alertModalDeleteCommunity.message = "Content Provider";
      if(title) {
        this.alertModalDeleteCommunity.message += " '"+title+"' ";
      }
      this.alertModalDeleteCommunity.message += "will be removed from your community. Are you sure?";
      this.alertModalDeleteCommunity.okButtonText = "Yes";
      this.alertModalDeleteCommunity.open();
    }
  }

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

      this.subResults = this._searchCommunityContentProvidersService.searchDataproviders(this.properties, this.community).subscribe(
          data => {
            //console.info("search Content Providers [total communityContentProviders:"+data.length+"]");
            this.communityContentProviders = data;

            this.communitySearchUtils.totalResults = data.length;
            this.communitySearchUtils.status = this.errorCodes.DONE;
            // if(this.communitySearchUtils.totalResults == 0 ){
            //   this.communitySearchUtils.status = this.errorCodes.NONE;
            // }
            this.disableForms = false;
            if(!this.triggered) {
              this.triggerInitialLoad();
            } else {
              var table = $('#dpTable').DataTable();
              table.clear();

              this.rerender();
            }

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

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

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

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

  goToCriteria(openaireId: string) {
    this._router.navigate(['criteria'], {
      queryParams: {
        communityId: this.community,
        openaireId: openaireId
      },
      relativeTo: this.route
    })
  }
}
