import { Component, ViewChild, OnInit, OnDestroy, ElementRef } from '@angular/core';
import { DivContentFormComponent } from "./div-help-content-form.component";
import { Subscription } from "rxjs";
import { HelpContentService } from "../../services/help-content.service";
import { DivHelpContent } from "../../domain/div-help-content";
import { ActivatedRoute, Router } from "@angular/router";
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 {Page} from "../../domain/page";
import {Title} from '@angular/platform-browser';

@Component({
    selector: 'edit-div-help-content',
    templateUrl: 'edit-div-help-content.component.html',
})

export class EditDivHelpContentComponent implements OnInit, OnDestroy{

    @ViewChild(DivContentFormComponent)
    public formComponent : DivContentFormComponent;

    public communityPid: string;
    public pageId: string;
    public page: Page;

    private sub: Subscription;

    private divHelpContent: DivHelpContent;

    public properties:EnvProperties = null;

    public showLoading: boolean = true;
    public errorMessage: string = '';
    public updateErrorMessage: string = '';

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

    ngOnInit() {
      this.route.data
        .subscribe((data: { envSpecific: EnvProperties }) => {
           this.properties = data.envSpecific;
           this.sub = this.route.queryParams.subscribe(params => {
             HelperFunctions.scroll();

            //let id = params['id'];
            let divContentId = params['classContentId'];
            this.communityPid = params['communityId'];
            this.pageId = params['pageId'];
            this.title.setTitle('Administration Dashboard | Edit Class Help Text');
             if(!divContentId) {
               this.router.navigate(['/classContents'], { queryParams: { "communityId": this.communityPid} });
             }

            this.getDivHelpContent(divContentId);
          });
        });
    }
    ngOnDestroy() {
        this.sub.unsubscribe();
    }

    handleError(message: string, error) {
        this.errorMessage = message;
        console.log('Server responded: ' + error);
        this.showLoading = false;
    }

    handleUpdateError(message: string, error) {
        this.updateErrorMessage = message;
        console.log('Server responded: ' + error);
        this.showLoading = false;
    }

    private getPage(pageId: string) {
      this._helpContentService.getPage(pageId,this.properties.adminToolsAPIURL).subscribe(
        page => {
          if( (this.communityPid == 'openaire' && !page.openaire)
            || (this.communityPid == 'connect' && !page.connect)
            || (this.communityPid != 'openaire' && this.communityPid != 'connect' && !page.communities)) {
            this.router.navigate(['/classContents'], { queryParams: { "communityId": this.communityPid} });
          } else {
            this.page = page;
            this.showLoading = false;
          }
        },
        error => this.handleError('System error retrieving page with id: '+pageId, error)
      );
    }

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

        this._helpContentService.getDivHelpContent(divContentId, this.properties.adminToolsAPIURL).subscribe(
            divHelpContent => {
              if(this.pageId) {
                this.getPage(this.pageId);
              }
              this.updateForm(divHelpContent);
              this.showLoading = false;
            },
            error => this.handleError('System error retrieving class help content', error));
      }
    }

    getDivId(divId: string) {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this.showLoading = true;

        this._helpContentService.getDivIdFull(divId, this.properties.adminToolsAPIURL).subscribe(
          div => {
            this.formComponent.selectedDiv = div;

            if(!this.pageId) {
              this.formComponent.getDivs("");
            }

            this.showLoading = false;
          },
          error => this.handleError('System error retrieving class', error)
       );
      }
    }

    private updateForm(divHelpContent : DivHelpContent) {
        this.divHelpContent = divHelpContent;

        this.getDivId(divHelpContent.divId as string);

        this.formComponent.myForm.patchValue((divHelpContent));
    }

    public saveCustom() {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        if(this.formComponent.myForm.valid) {
            this.showLoading = true;
            this.updateErrorMessage = "";

            let divHelpContent : DivHelpContent = this.formComponent.myForm.value;

            this._helpContentService.insertOrUpdateDivHelpContent(divHelpContent, this.properties.adminToolsAPIURL).subscribe(
                _ => {
                  if(this.pageId) {
                    this.router.navigate( ['/classContents/'], { queryParams: { "communityId": this.communityPid, "pageId": this.pageId  } } );
                  } else {
                    this.router.navigate(['/classContents'], { queryParams: { "communityId": this.communityPid } } );
                  }
                  this.showLoading = false;
                },
                err => this.handleUpdateError('System error updating class content', err)
            );
        } else {
            this.errorMessage = "Please fill all required fields";
        }
      }
    }

    public cancelCustom() {
      this.errorMessage = "";
      this.updateErrorMessage = "";

      if(this.pageId) {
        this.router.navigate( ['/classContents/'], { queryParams: { "communityId": this.communityPid, "pageId": this.pageId  } } );
      } else {
        this.router.navigate(['/classContents'], { queryParams: { "communityId": this.communityPid } } );
      }
    }
}
