/**
 * Created by stefania on 7/13/17.
 */
import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {HelpContentService} from '../../services/help-content.service';
import {FormGroup} from '@angular/forms';
import {PageFormComponent} from './page-form.component';
import {CheckPage, Page} from '../../domain/page';
import {Community} from '../../domain/community';
import {Entity} from '../../domain/entity';
import {EnvProperties} from '../../openaireLibrary/utils/properties/env-properties';
import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {HelperFunctions} from '../../openaireLibrary/utils/HelperFunctions.class';
import {UserManagementService} from '../../openaireLibrary/services/user-management.service';
import {Title} from '@angular/platform-browser';
import {StringUtils} from '../../openaireLibrary/utils/string-utils.class';

@Component({
  selector: 'pages',
  templateUrl: './pages.component.html',
})

export class PagesComponent implements OnInit {

  @ViewChild('AlertModalSavePage') alertModalSavePage;
  @ViewChild('AlertModalUpdatePage') alertModalUpdatePage;
  @ViewChild('AlertModalDeletePages') alertModalDeletePages;
  private selectedPages: string[] = [];

  @ViewChild(PageFormComponent)
  public formComponent: PageFormComponent;

  public checkboxes: CheckPage[] = [];

  public pages: Page[] = [];
  public pageWithDivIds: string[] = [];

  //public errorMessage: string;

  public formGroup: FormGroup;

  private searchText: RegExp = new RegExp('');
  public keyword: string = '';

  public communities: Community[] = [];

  public selectedCommunityPid: string;

  public pagesType: string;
  public properties: EnvProperties = null;

  public showLoading: boolean = true;
  public errorMessage: string = '';
  public updateErrorMessage: string = '';
  public modalErrorMessage: string = '';
  public isPortalAdministrator = null;

  constructor(private element: ElementRef, private route: ActivatedRoute,
              private title: Title,
              private _router: Router, private _helpContentService: HelpContentService,
              private userManagementService: UserManagementService) {
  }

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

        this.route.queryParams.subscribe(params => {
          HelperFunctions.scroll();
          this.title.setTitle('Administration Dashboard | Pages');
          this.pagesType = '';
          if (params['type']) {
            this.pagesType = params['type'];
            this.title.setTitle('Administration Dashboard | ' + StringUtils.capitalize(this.pagesType) + ' Pages');
          }

          this.keyword = '';
          this.userManagementService.getUserInfo().subscribe( user => {
            this.selectedCommunityPid = params['communityId'];
            this.applyCommunityFilter(this.selectedCommunityPid);
            this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.selectedCommunityPid;
          });
          //this.getCommunities();
        });
      });
  }

  getPages(community_pid: string) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      this.showLoading = true;
      this.updateErrorMessage = '';
      this.errorMessage = '';

      this.pageWithDivIds = [];

      let parameters = '';
      if (this.pagesType) {
        parameters = '?page_type=' + this.pagesType;
      }
      if (community_pid) {
        this._helpContentService.getCommunityPages(community_pid, parameters, this.properties.adminToolsAPIURL).subscribe(
          pages => {
            this.pagesReturned(pages);
            //if(!this.pagesType || this.pagesType == "link") {
            this.getPagesWithDivIds(community_pid);
            //} else {
            //this.showLoading = false;
            //}
          },
          error => this.handleError('System error retrieving pages', error)
        );
      } else {
        this._helpContentService.getPagesFull(this.properties.adminToolsAPIURL, null).subscribe(
          pages => {
            this.pagesReturned(pages);
            this.showLoading = false;
          },
          error => this.handleError('System error retrieving pages', error)
        );
      }
    }
  }

  getPagesWithDivIds(community_pid: string) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      this._helpContentService.getPagesWithDivIds(community_pid, this.properties.adminToolsAPIURL).subscribe(
        pages => {
          this.pageWithDivIds = pages;
          this.showLoading = false;
        },
        error => this.handleError('System error retrieving information about pages\' classes', error));
    }
  }

  pagesReturned(pages: Page[]) {
    this.pages = pages;
    this.checkboxes = [];

    if (pages) {
      pages.forEach(_ => {
        this.checkboxes.push(<CheckPage>{page: _, checked: false});
      });
    }
  }

  /*
      getCommunities() {
          this._helpContentService.getCommunities(this.properties.adminToolsAPIURL).subscribe(
              communities => {
                  this.communities = communities;
                  this.selectedCommunityPid = this.communities[0].pid;
                  this.getPages(this.selectedCommunityPid);
                  this.getPagesWithDivIds(this.selectedCommunityPid);
          },
          error => this.handleError('System error retrieving communities', error));
      }
  */

  public toggleCheckBoxes(event) {
    this.checkboxes.forEach(_ => _.checked = event.target.checked);
  }

  public applyCheck(flag: boolean) {
    this.checkboxes.forEach(_ => _.checked = flag);
  }

  public getSelectedPages(): string[] {
    return this.checkboxes.filter(page => page.checked == true).map(checkedPage => checkedPage.page).map(res => res._id);
  }

  private deletePagesFromArray(ids: string[]): void {
    for (let id of ids) {
      let i = this.checkboxes.findIndex(_ => _.page._id == id);
      this.checkboxes.splice(i, 1);
    }
  }

  public confirmDeletePage(id: string) {
    //this.deleteConfirmationModal.ids = [id];
    //this.deleteConfirmationModal.showModal();
    this.selectedPages = [id];
    this.confirmModalOpen();
  }

  public confirmDeleteSelectedPages() {
    //this.deleteConfirmationModal.ids = this.getSelectedPages();
    //this.deleteConfirmationModal.showModal();
    this.selectedPages = this.getSelectedPages();
    this.confirmModalOpen();
  }

  private confirmModalOpen() {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      this.alertModalDeletePages.cancelButton = true;
      this.alertModalDeletePages.okButton = true;
      this.alertModalDeletePages.alertTitle = 'Delete Confirmation';
      this.alertModalDeletePages.message = 'Are you sure you want to delete the selected page(s)?';
      this.alertModalDeletePages.okButtonText = 'Yes';
      this.alertModalDeletePages.open();
    }
  }

  public confirmedDeletePages(data: any) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      this.showLoading = true;
      this.updateErrorMessage = '';

      this._helpContentService.deletePages(this.selectedPages, this.properties.adminToolsAPIURL).subscribe(
        _ => {
          this.deletePagesFromArray(this.selectedPages);
          this.showLoading = false;
        },
        error => this.handleUpdateError('System error deleting the selected pages', error)
      );
    }
  }

  public editPage(i: number) {
    let page: Page = this.checkboxes[i].page;
    this.formGroup.patchValue(page);
    this.formComponent.setEntities(page.entities as Entity[]);

    //console.info(this.formGroup.value);
    //this.updateModal.showModal();
    this.modalErrorMessage = '';
    this.pagesModalOpen(this.alertModalUpdatePage, 'Update', 'Update Page');
  }

  public newPage() {
    this.formComponent.reset();
    this.modalErrorMessage = '';
    this.pagesModalOpen(this.alertModalSavePage, 'Save', 'Add a new Page');
  }

  private pagesModalOpen(modal: any, title: string, yesBtn: string) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      modal.cancelButton = true;
      modal.okButton = true;
      modal.alertTitle = title;
      modal.okButtonText = yesBtn;
      modal.open();
    }
  }

  public pageSaveConfirmed(data: any) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      if (!this.formGroup.valid) {
        this.pagesModalOpen(this.alertModalSavePage, 'Save', 'Add a new Page');
        this.modalErrorMessage = 'Please fill in all required fields marked with *';
      } else {
        this.modalErrorMessage = '';
        this._helpContentService.savePage(<Page>this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
          page => {
            this.pageSavedSuccessfully(page);
          },
          error => this.handleUpdateError('System error creating page', error)
        );
      }
    }
  }

  public pageUpdateConfirmed(data: any) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      if (!this.formGroup.valid) {
        this.pagesModalOpen(this.alertModalUpdatePage, 'Update', 'Update Page');
        this.modalErrorMessage = 'Please fill in all required fields marked with *';
      } else {
        this._helpContentService.updatePage(<Page>this.formGroup.value, this.properties.adminToolsAPIURL).subscribe(
          page => {
            this.pageUpdatedSuccessfully(page);
          },
          error => this.handleUpdateError('System error updating page', error)
        );
      }
    }
  }

  public pageSavedSuccessfully(page: Page) {
    this.checkboxes.push(<CheckPage>{page: page, checked: false});
    this.applyCheck(false);
  }

  public pageUpdatedSuccessfully(page: Page) {
    this.checkboxes.find(checkItem => checkItem.page._id == page._id).page = page;
    this.applyCheck(false);
  }

  public filterBySearch(text: string) {
    this.searchText = new RegExp(text, 'i');
    this.applyFilter();
  }

  public applyFilter() {
    this.checkboxes = [];
    this.pages.filter(item => this.filterPages(item)).forEach(
      _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
    );
  }

  public filterPages(page: Page): boolean {
    let textFlag = this.searchText.toString() == '' || (page.route + ' ' + page.name).match(this.searchText) != null;
    return textFlag;
  }

  handleError(message: string, error) {
    // if(error == null) {
    //     this.formComponent.reset();
    // } else {
    this.errorMessage = message;// + ' (Server responded: ' + error + ')';
    console.log('Server responded: ' + error);
    //}

    this.showLoading = false;
  }

  handleUpdateError(message: string, error) {
    if (error == null) {
      this.formComponent.reset();
    } else {
      this.updateErrorMessage = message;// + ' (Server responded: ' + error + ')';
      console.log('Server responded: ' + error);
    }

    this.showLoading = false;
  }

  // public filterByCommunity(event: any) {
  //     this.selectedCommunityPid = event.target.value;
  //     this.applyCommunityFilter(this.selectedCommunityPid);
  // }

  public applyCommunityFilter(community_pid: string) {
    this.getPages(community_pid);
  }

  public togglePages(status: boolean, ids: string[]) {
    if (!Session.isLoggedIn()) {
      this._router.navigate(['/user-info'], {queryParams: {'errorCode': LoginErrorCodes.NOT_VALID, 'redirectUrl': this._router.url}});
    } else {
      this.updateErrorMessage = '';

      this._helpContentService.togglePages(this.selectedCommunityPid, ids, status, this.properties.adminToolsAPIURL).subscribe(
        () => {
          for (let id of ids) {
            let i = this.checkboxes.findIndex(_ => _.page._id == id);
            this.checkboxes[i].page.isEnabled = status;
          }
          this.applyCheck(false);
        },
        error => this.handleUpdateError('System error changing the status of the selected page(s)', error)
      );
    }
  }

  public capitalizeFirstLetter(str: string) {
    return str.charAt(0).toUpperCase() + str.slice(1);
  }
}
