import {Component, OnInit, Input, ViewChild, ViewEncapsulation}                        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 {HelpContentService}                              from '../../services/help-content.service';
import {EnvProperties}                                   from '../../openaireLibrary/utils/properties/env-properties';

import {ErrorCodes}                                      from '../../openaireLibrary/utils/properties/errorCodes';
import {SearchUtilsClass}                                from '../../openaireLibrary/searchPages/searchUtils/searchUtils.class';
import {ZenodoCommunitiesService} from '../../openaireLibrary/connect/zenodoCommunities/zenodo-communities.service';
import {ZenodoCommunityInfo} from '../../openaireLibrary/connect/zenodoCommunities/zenodoCommunityInfo';

import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import{ManageZenodoCommunitiesService} from '../../services/manageZenodoCommunities.service';

@Component({
    selector: 'manage-zenodo-communities',
    templateUrl: './manage-zenodo-communities.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 ManageZenodoCommunitiesComponent implements OnInit {
    @Input() properties:EnvProperties = null;
    @Input() communityId = null;

    @Input() searchUtils:SearchUtilsClass = null;

    errorCodes: ErrorCodes;
    public rowsOnPage = 10;
    @Input() masterCommunity = null;
    @Input() selectedCommunities = [];

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

    @ViewChild('AlertModalDeleteCommunity') alertModalDeleteCommunity;
    selectedToDelete = null;
    constructor (private route: ActivatedRoute,
                 private _router: Router,
                 public _fb: FormBuilder,
                 private _helpContentService: HelpContentService,
                 private _ΖenodoCommunitieService: ZenodoCommunitiesService,
               private _manageZenodoCommunitiesService: ManageZenodoCommunitiesService) {

       this.errorCodes = new ErrorCodes();

    }

    ngOnInit() {


        this.searchUtils.keyword = "";
        this.dtOptions = {
          // "paging": true,
          // "searching": true,
          // "lengthChange": false,
          "pageLength": this.rowsOnPage,
          "language": {
              "search": "",
              "searchPlaceholder": "Search projects..."
            }

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

          this.rerender();
        }

        this.searchUtils.totalResults = this.selectedCommunities.length;
     }

     public ngOnDestroy() {

       $.fn['dataTable'].ext.search.pop();
     }
     rerender(): void {
       if(this.datatableElement.dtInstance){
          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.searchUtils.keyword )) {
            return true;
          }
          return false;
        });

        //console.info("ngAfterViewInit");
        this.searchUtils.totalResults = this.selectedCommunities.length;

     }

     filterData(row: any, query: string) {
       let returnValue: boolean = false;

       if(query) {
         for(var i=0; i <3; 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.searchUtils.page=page;

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

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

    public confirmedDeleteCommunity(data : any) {

      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
         this._manageZenodoCommunitiesService.removeZCommunity(this.properties, this.communityId,this.selectedToDelete.openaireId ).subscribe(
          data => {
             var pos = -1;
            for(var i=0;  i< this.selectedCommunities.length;i++) {
               if( this.selectedCommunities[i].id == this.selectedToDelete.id) {
                pos= i;
                break;
              }
            }
             if(pos != -1){
              this.selectedCommunities.splice(pos, 1);
              this.searchUtils.totalResults = this.selectedCommunities.length;
            }
            this.searchUtils.totalResults = this.selectedCommunities.length;
            var table = $('#dpTable').DataTable();
            table.clear();
            this.rerender();

          },
          err => {
            console.log(err.status);
          }/*,
          () => {
            console.info("completed remove");
          }*/
        )
      }
    }

    public removeCommunity( comm) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this.selectedToDelete = comm;
        this.alertModalDeleteCommunity.cancelButton = true;
        this.alertModalDeleteCommunity.okButton = true;
        this.alertModalDeleteCommunity.alertTitle = "Remove zenodo community?";
        let title = "";
        if(comm.title) {
          title = comm.title;
        }


        this.alertModalDeleteCommunity.message = "Zenodo community";
        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();
      }
    }


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


}
