import {Component, ElementRef, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {HelpContentService} from '../../services/help-content.service';
import {UntypedFormArray, UntypedFormBuilder, UntypedFormGroup, Validators} from '@angular/forms';
import {CheckPage, Page} from '../../utils/entities/adminTool/page';
import {Entity} from '../../utils/entities/adminTool/entity';
import {EnvProperties} from '../../utils/properties/env-properties';
import {Session} from '../../login/utils/helper.class';
import {UserManagementService} from '../../services/user-management.service';
import {Subscriber} from 'rxjs';
import {PortalUtils} from '../portal/portalHelper';
import {properties} from '../../../../environments/environment';
import {Option} from '../../sharedComponents/input/input.component';
import {AlertModal} from '../../utils/modal/alert';
import {Title} from '@angular/platform-browser';
import {StringUtils} from '../../utils/string-utils.class';
import {StakeholderService} from '../../monitor/services/stakeholder.service';
import {CommunityInfo} from "../../connect/community/communityInfo";
import {Stakeholder} from "../../monitor/entities/stakeholder";
import {CommunityService} from "../../connect/community/community.service";
import {ClearCacheService} from "../../services/clear-cache.service";
import {NotificationHandler} from "../../utils/notification-handler";
import {PluginsService} from "../../services/plugins.service";

@Component({
  selector: 'pages',
  templateUrl: './pages.component.html'
})
export class PagesComponent implements OnInit {
  
  @ViewChild('editModal') editModal: AlertModal;
  @ViewChild('deleteModal') deleteModal: AlertModal;
  private selectedPages: string[] = [];
  
  public checkboxes: CheckPage[] = [];
  
  public pages: Page[] = [];
  public pageWithDivIds: string[] = [];
  
  //public errorMessage: string;
  
  public pageForm: UntypedFormGroup;
  
  private searchText: RegExp = new RegExp('');
  public keyword: string = '';
  
  public portal: string;
  public type: any;
	public name: string;
  public entity: CommunityInfo | Stakeholder;
  public showLogo: boolean = true;
  public pagesType: string;
  public properties: EnvProperties = properties;
  
  public showLoading: boolean = true;
  public isPortalAdministrator = null;
  public filterForm: UntypedFormGroup;
  public typeOptions = [{label: 'Search', value: 'search'}, {
    label: 'Share',
    value: 'share'
  }, {label: 'Landing', value: 'landing'}, {label: 'HTML', value: 'html'}, {
    label: 'Link',
    value: 'link'
  }, {label: 'Other', value: 'other'}];
  public entitiesCtrl: UntypedFormArray;
  allEntities: Option[] = [];
  private subscriptions: any[] = [];
  public portalUtils: PortalUtils = new PortalUtils();
  private index: number;
  pageHelpContentsCount = {};
  pageClassContentsCount = {};
  pagePluginTemplatesCount = {};
  constructor(private element: ElementRef, private route: ActivatedRoute,
              private title: Title,
              private _router: Router, private _helpContentService: HelpContentService,
              private _pluginsService: PluginsService,
              private userManagementService: UserManagementService, private _fb: UntypedFormBuilder,
              private communityService: CommunityService,
							private stakeholderService: StakeholderService,
              private _clearCacheService: ClearCacheService) {
  }
  
  ngOnInit() {
    this.filterForm = this._fb.group({
      keyword: [''],
      type: ['all', Validators.required]
    });
    this.subscriptions.push(this.filterForm.get('keyword').valueChanges.subscribe(value => {
      this.searchText = new RegExp(value, 'i');
      this.applyFilters();
    }));
    this.subscriptions.push(this.filterForm.get('type').valueChanges.subscribe(value => {
      this.applyFilters();
    }));
    this.subscriptions.push(this.route.queryParams.subscribe(params => {
      this.pagesType = '';
      if (params['type']) {
        // this.pagesType = params['type'];
        this.filterForm.get('type').setValue(params['type']);
      }
      this.portal = (this.route.snapshot.data.portal) ? this.route.snapshot.data.portal : this.route.snapshot.params[this.route.snapshot.data.param];
      if (this.route.snapshot.data.portal) {
        this.name = StringUtils.capitalize(this.portal);
        this.title.setTitle(StringUtils.capitalize(this.portal) + ' | Pages');
      } else if (this.route.snapshot.params[this.route.snapshot.data.param]) {
        this.type = this.route.snapshot.data.param;
				if(this.route.snapshot.data.param === 'stakeholder') {
					this.subscriptions.push(this.stakeholderService.getStakeholderAsObservable().subscribe(stakeholder => {
						if(stakeholder) {
							this.name = stakeholder.name;
							this.entity = stakeholder;
							this.title.setTitle(this.name + ' | Pages');
						}
					}));
				} else {
          this.subscriptions.push(this.communityService.getCommunityAsObservable().subscribe(community => {
            if(community) {
              this.showLogo = false;
              this.name = community.shortTitle;
              this.entity = community;
              this.title.setTitle(this.name + ' | Pages');
            }
          }));
				}
      } else {
        this.title.setTitle('Administrator Dashboard | Pages');
      }
      this.keyword = '';
      this.subscriptions.push(this.userManagementService.getUserInfo().subscribe(user => {
        this.applyPortalFilter(this.portal);
        this.isPortalAdministrator = Session.isPortalAdministrator(user) && !this.portal;
      }));
    }));
    this.subscriptions.push(this._helpContentService.getEntities(this.properties.adminToolsAPIURL).subscribe(
      entities => {
        this.allEntities = [];
        entities.forEach(entity => {
          this.allEntities.push({
            label: entity.name,
            value: entity
          });
        });
      },
      error => this.handleError('System error retrieving pages', error)));
    if (this.portal) {
      this.getCountsPerPID(this.portal);
    }
    this.getPluginTemplatesContentsCounts()
  }
  
  ngOnDestroy(): void {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      } else if (value instanceof Function) {
        value();
      }
    });
  }
  
  getPages(portal: string) {
    this.showLoading = true;
    this.pageWithDivIds = [];
    let parameters = '';
    if (this.pagesType) {
      parameters = '?page_type=' + this.pagesType;
    }
    if (portal) {
      this.subscriptions.push(this._helpContentService.getCommunityPagesByType(portal, parameters, this.properties.adminToolsAPIURL).subscribe(
        pages => {
          this.pagesReturned(pages);
          //if(!this.pagesType || this.pagesType == "link") {
          this.getPagesWithDivIds(portal);
          //} else {
          //this.showLoading = false;
          //}
        },
        error => this.handleError('System error retrieving pages', error)
      ));
    } else {
      this.subscriptions.push(this._helpContentService.getAllPagesFull(this.properties.adminToolsAPIURL).subscribe(
        pages => {
          this.pagesReturned(pages);
          this.showLoading = false;
        },
        error => this.handleError('System error retrieving pages', error)
      ));
    }
  }
  
  getPagesWithDivIds(portal: string) {
    this.subscriptions.push(this._helpContentService.getPageIdsFromDivIds(portal, 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});
      });
    }
  }
  
  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.pages.findIndex(_ => _._id == id);
      this.pages.splice(i, 1);
    }
    this.applyFilters();
  }
  
  public confirmDeletePage(id: string) {
    this.selectedPages = [id];
    this.confirmModalOpen();
  }
  
  public confirmDeleteSelectedPages() {
    this.selectedPages = this.getSelectedPages();
    this.confirmModalOpen();
  }
  
  private confirmModalOpen() {
    this.deleteModal.alertTitle = 'Delete Confirmation';
    this.deleteModal.message = 'Are you sure you want to delete the selected page(s)?';
    this.deleteModal.okButtonText = 'Yes';
    this.deleteModal.open();
  }
  
  public confirmedDeletePages() {
    this.showLoading = true;
    this.subscriptions.push(this._helpContentService.deletePages(this.selectedPages, this.properties.adminToolsAPIURL).subscribe(
      _ => {
        this.deletePagesFromArray(this.selectedPages);
        NotificationHandler.rise('Pages have been <b>successfully deleted</b>');
        this.showLoading = false;
        // this._clearCacheService.clearCache("Pages deleted");
        // this._clearCacheService.purgeBrowserCache("Pages deleted", this.portal);
      },
      error => this.handleUpdateError('System error deleting the selected pages', error)
    ));
  }
  
  public editPage(i: number) {
    this.entitiesCtrl = this._fb.array([]);
    let page: Page = this.checkboxes[i].page;
    this.index = this.pages.findIndex(value => value._id === page._id);
    this.pageForm = this._fb.group({
      _id: this._fb.control(page._id),
      route: this._fb.control(page.route, Validators.required),
      name: this._fb.control(page.name, Validators.required),
      isEnabled: this._fb.control(page.isEnabled),
      portalType: this._fb.control(page.portalType, Validators.required),
			portalPid: this._fb.control(page.portalPid),
      top: this._fb.control(page.top),
      bottom: this._fb.control(page.bottom),
      left: this._fb.control(page.left),
      right: this._fb.control(page.right),
      type: this._fb.control(page.type, Validators.required),
      entities: this.entitiesCtrl
    });
    this.pageForm.get('portalType').disable();
    for (let i = 0; i < page.entities.length; i++) {
      this.entitiesCtrl.push(this._fb.control(page.entities[i]));
    }
    this.pagesModalOpen('Edit Page', 'Save changes');
  }
  
  public newPage() {
    if (this.pageForm) {
      this.pageForm.get('portalType').enable();
    }
    this.entitiesCtrl = this._fb.array([]);
    this.pageForm = this._fb.group({
      _id: this._fb.control(null),
      route: this._fb.control('', Validators.required),
      name: this._fb.control('', Validators.required),
      isEnabled: this._fb.control(true),
      portalType: this._fb.control('', Validators.required),
			portalPid: this._fb.control(null),
      top: this._fb.control(true),
      bottom: this._fb.control(true),
      left: this._fb.control(true),
      right: this._fb.control(true),
      type: this._fb.control(this.typeOptions[0].value, Validators.required),
      entities: this.entitiesCtrl,
    });
    this.pagesModalOpen('Create Page', 'Create');
  }
  
  private pagesModalOpen(title: string, yesBtn: string) {
    this.editModal.okButtonLeft = false;
    this.editModal.alertTitle = title;
    this.editModal.okButtonText = yesBtn;
    this.editModal.open();
  }
  
  public pageSaveConfirmed(data: any) {
    this.showLoading = true;
    if (!this.pageForm.getRawValue()._id) {
      this.subscriptions.push(this._helpContentService.savePage(<Page>this.pageForm.getRawValue(), this.properties.adminToolsAPIURL).subscribe(
        page => {
          this.pageSavedSuccessfully(page, true);
          NotificationHandler.rise('Page <b>' + page.name + '</b> has been <b>successfully created</b>');
          // this._clearCacheService.clearCache("Page saved");
          // this._clearCacheService.purgeBrowserCache("Page saved", this.portal);
        },
        error => this.handleUpdateError('System error creating page', error)
      ));
    } else {
      this.subscriptions.push(this._helpContentService.updatePage(<Page>this.pageForm.getRawValue(), this.properties.adminToolsAPIURL).subscribe(
        page => {
          this.pageSavedSuccessfully(page, false);
          NotificationHandler.rise('Page <b>' + page.name + '</b> has been <b>successfully updated</b>');
          // this._clearCacheService.clearCache("Page updated");
          // this._clearCacheService.purgeBrowserCache("Page updated", this.portal);
        },
        error => this.handleUpdateError('System error updating page', error)
      ));
    }
  }
  
  public pageSavedSuccessfully(page: Page, isNew: boolean) {
    if (isNew) {
      this.pages.push(page);
    } else {
      this.pages[this.index] = page;
    }
    this.applyFilters();
    this.applyCheck(false);
    this.showLoading = false;
  }
  
  public applyFilters() {
    this.checkboxes = [];
    this.pages.filter(item => this.filterByType(item)).forEach(
      _ => this.checkboxes.push(<CheckPage>{page: _, checked: false})
    );
    this.checkboxes = this.checkboxes.filter(item => this.filterPages(item.page));
  }
  
  public filterByType(page: Page): boolean {
    let type = this.filterForm.get("type").value;
    return type == "all" || (type == page.type);
  }
  
  public filterPages(page: Page): boolean {
    return this.searchText.toString() == '' || (page.route + ' ' + page.name + ' ' + page.portalType).match(this.searchText) != null;
  }
  
  handleError(message: string, error = null) {
    if(error) {
      console.error('Server responded: ' + error);
    }
    NotificationHandler.rise(message, 'danger');
    this.showLoading = false;
  }
  
  handleUpdateError(message: string, error = null) {
    if (!error) {
      this.pageForm = this._fb.group({
        route: this._fb.control('', Validators.required),
        name: this._fb.control('', Validators.required),
        isEnabled: this._fb.control(true),
        portalType: this._fb.control('', Validators.required),
        top: this._fb.control(true),
        bottom: this._fb.control(true),
        left: this._fb.control(true),
        right: this._fb.control(true),
        type: this._fb.control(this.typeOptions[0].value, Validators.required),
        entities: this.entitiesCtrl,
        _id: this._fb.control(''),
      });
    } else {
      console.error('Server responded: ' + error);
    }
    NotificationHandler.rise(message, 'danger');
    this.showLoading = false;
  }
  
  public getEntitiesAsString(page: Page): string {
    if (page.entities) {
      return (<any[]>page.entities).map((page: Entity) => page.name).join(',');
    }
    return '';
  }
  
  public applyPortalFilter(portal: string) {
    this.getPages(portal);
  }
  
  public togglePages(status: boolean, ids: string[]) {
    this.subscriptions.push(this._helpContentService.togglePages(this.portal, 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);
        this._clearCacheService.clearCacheInRoute("Page's status changed",this.portal, "/");
        this._clearCacheService.purgeBrowserCache("Page's status changed", this.portal);
      },
      error => this.handleUpdateError('System error changing the status of the selected page(s)', error)
    ));
  }
  
  selectAll() {
    let checked = this.getSelectedPages().length != this.checkboxes.length;
    for (let check of this.checkboxes) {
      check.checked = checked;
    }
  }
  
  getCountsPerPID(community_pid: string) {
    this.subscriptions.push(this._helpContentService.countCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL, false).subscribe(
      pageHelpContentsCount => {
        this.pageHelpContentsCount = pageHelpContentsCount;
      },
      error => this.handleError('System error retrieving page contents', error)));
    this.subscriptions.push(this._helpContentService.countCommunityPageHelpContents(community_pid, this.properties.adminToolsAPIURL, true).subscribe(
      pageClassContentsCount => {
        this.pageClassContentsCount = pageClassContentsCount;
      },
      error => this.handleError('System error retrieving page contents', error)));
    this.subscriptions.push(this._pluginsService.countPluginTemplatePerPage( this.properties.adminToolsAPIURL, community_pid).subscribe(
      countPlugins => {
        this.pagePluginTemplatesCount = countPlugins;
      },
      error => this.handleError('System error retrieving page contents', error)));
  }

  getPluginTemplatesContentsCounts() {
    this.subscriptions.push(this._pluginsService.countPluginTemplatePerPageForAllPortals( this.properties.adminToolsAPIURL).subscribe(
      countPlugins => {
        this.pagePluginTemplatesCount = countPlugins;
      },
      error => this.handleError('System error retrieving page contents', error)));
  }

}
