import {Component, OnInit, Input}                        from '@angular/core';
import {SimpleChanges, OnChanges}                        from '@angular/core';
import {FormGroup, FormArray, FormBuilder, Validators}   from '@angular/forms';
import {ActivatedRoute, Router}                          from '@angular/router';

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: 'add-zenodo-communities',
    templateUrl: './add-zenodo-communities.component.html',
})

export class AddZenodoCommunitiesComponent implements OnInit {

    public zenodoCommunities = null; // zenodo search API results
    public totalZenodoCommunities = null;
    @Input() properties:EnvProperties = null;
    @Input() communityId = null;

    public zenodoCommunitySearchUtils:SearchUtilsClass = new SearchUtilsClass();

    errorCodes: ErrorCodes;
    public rowsOnPage = 10;
    @Input() masterCommunity = null;
    @Input() selectedCommunities = [];
    newlySelectedCommunities = [];
    constructor (private route: ActivatedRoute,
                 private _router: Router,
                 public _fb: FormBuilder,
                 private _helpContentService: HelpContentService,
                 private _zenodoCommunitieService: ZenodoCommunitiesService,
               private _manageZenodoCommunitiesService: ManageZenodoCommunitiesService) {

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

    ngOnInit() {
      this.zenodoCommunitySearchUtils.keyword = "";
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this.zenodoCommunitySearchUtils.status = this.errorCodes.LOADING;
        this.newlySelectedCommunities = [];
        if (this.communityId != null && this.communityId != '') {
            this._zenodoCommunitieService.getZenodoCommunities(this.properties, this.properties.zenodoCommunities+"?page="+this.zenodoCommunitySearchUtils.page+"&size="+this.rowsOnPage).subscribe(
                result  => {
                         this.zenodoCommunities = result[0];
                         this.totalZenodoCommunities = result[1];
                         this.zenodoCommunitySearchUtils.totalResults = result[1];
                         this.zenodoCommunitySearchUtils.page = 1;
                         this.zenodoCommunitySearchUtils.size =this.rowsOnPage;
                         if(this.totalZenodoCommunities == 0){
                           this.zenodoCommunitySearchUtils.status = this.errorCodes.NONE;
                         }else{
                           this.zenodoCommunitySearchUtils.status = this.errorCodes.DONE;
                         }

            },
            error => {
              this.zenodoCommunitySearchUtils.status = this.errorCodes.ERROR;
            }
          );
        }
      }

    }

    public goTo(page:number = 1) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this.zenodoCommunitySearchUtils.page=page;
        this.zenodoCommunitySearchUtils.status = this.errorCodes.LOADING;
        this._zenodoCommunitieService.getZenodoCommunities(this.properties,
          this.properties.zenodoCommunities+"?page="+this.zenodoCommunitySearchUtils.page
          +"&size="+this.rowsOnPage
        +((this.zenodoCommunitySearchUtils.keyword)?("&q="+this.zenodoCommunitySearchUtils.keyword):"")
        ).subscribe(
            result  => {
              this.zenodoCommunities = result[0];
              this.totalZenodoCommunities = result[1];
              this.zenodoCommunitySearchUtils.totalResults = result[1];
              this.zenodoCommunitySearchUtils.size =this.rowsOnPage;
              if(this.totalZenodoCommunities == 0){
                this.zenodoCommunitySearchUtils.status = this.errorCodes.NONE;
              }else{
                this.zenodoCommunitySearchUtils.status = this.errorCodes.DONE;
              }

       },
       error => {
         this.zenodoCommunitySearchUtils.status = this.errorCodes.ERROR;
       }
       );
      }
    }

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


    public addCommunity(community) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        this._manageZenodoCommunitiesService.addZCommunity(this.properties, this.communityId, community.id ).subscribe(
          data => {
            // this.undo[project.id] = data.id;
            community["openaireId"]=data.id;
            this.selectedCommunities.push(community);
            this.newlySelectedCommunities.push(community)
          },
          err => {
            console.log(err.status);
          }/*,
          () => {
            console.info("completed ADD");
          }*/
        )
      }
    }

    public removeCommunity( comm) {
      if(!Session.isLoggedIn()){
        this._router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this._router.url} });
      } else {
        var openaireId = this.getOpenaireId(comm);
        this._manageZenodoCommunitiesService.removeZCommunity(this.properties, this.communityId,openaireId, ).subscribe(
          data => {
            var pos = -1;
            for(var i=0;  i< this.selectedCommunities.length;i++) {
              if( this.selectedCommunities[i].id == comm.id) {
                pos= i;
                break;
              }
            }
            if(pos != -1){
              this.selectedCommunities.splice(pos, 1);
            }
            for(var i=0;  i< this.newlySelectedCommunities.length;i++) {
              if( this.newlySelectedCommunities[i].id == comm.id) {
                pos= i;
                break;
              }
            }
            if(pos != -1){
              this.newlySelectedCommunities.splice(pos, 1);
            }

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

    public inThelist(community: any, list): any {
      for(let com of list) {
        if(com.id == community.id) {
          return  true;
        }
      }
      return false;
    }
      public getOpenaireId(community: any): string {
        for(let com of this.selectedCommunities) {
          if(com.id == community.id) {
            return  com.openaireId;
          }
        }
        return null;
      }
}
