import { Component, ViewChild, OnInit, ElementRef } from '@angular/core';
import { FormGroup } from "@angular/forms";
import { ActivatedRoute, Router } from "@angular/router";
//import { Location } from "@angular/common";
import { HelpContentService } from "../../services/help-content.service";
import { HtmlPageContentService } from "./html-page-content.service";
import { HtmlPageContent, CheckHtmlPageContent } from "../../domain/html-page-content";
import { HtmlPageContentFormComponent } from "./html-page-content-form.component";

import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';
import { Subscription } from "rxjs";

import {Session} from '../../openaireLibrary/login/utils/helper.class';
import {LoginErrorCodes} from '../../openaireLibrary/login/utils/guardHelper.class';
import {HelperFunctions} from "../../openaireLibrary/utils/HelperFunctions.class";
import {Title} from '@angular/platform-browser';
declare var UIkit: any;

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

export class EditHtmlPageContentComponent implements OnInit {
    @ViewChild(HtmlPageContentFormComponent)
    public formComponent : HtmlPageContentFormComponent;

    communityPid: string;
    pageId: string;
    pageName: string = "";
    //public mode: string = "edit";

    private sub: Subscription;

    private htmlPageContent: HtmlPageContent;

    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,
        private _htmlContentService: HtmlPageContentService) {
          this.router.routeReuseStrategy.shouldReuseRoute = function(){
            return false;
          }
    }

    ngOnInit() {
      this.route.data
        .subscribe((data: { envSpecific: EnvProperties }) => {
           this.properties = data.envSpecific;
           this.sub = this.route.queryParams.subscribe(params => {
             HelperFunctions.scroll();
             this.title.setTitle('Administration Dashboard | Edit HTML page');
             this.communityPid = params['communityId'];
             this.pageId = params['pageId'];

             this.getPage(this.communityPid, this.pageId);
           });
      });
    }
    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(communityId: string, pageId: string) {
      if(!Session.isLoggedIn()){
        this.router.navigate(['/user-info'], { queryParams: { "errorCode": LoginErrorCodes.NOT_VALID, "redirectUrl":  this.router.url} });
      } else {
        this._helpContentService.getPage(pageId, this.properties.adminToolsAPIURL).subscribe(
          page => {
            this.pageName = page.name;
            this.getHtmlPageContent(communityId, page.route);
          },
          error => this.handleError('System error retrieving page', error));
      }
    }

    private getHtmlPageContent(communityId: string, pageRoute: 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._htmlContentService.getHtmlPageContent(communityId, pageRoute, this.properties.adminToolsAPIURL).subscribe(
          htmlPageContent => {
            if(htmlPageContent.length > 0) {
              this.updateForm(htmlPageContent[0]);
            }
            this.showLoading = false;
          },
          error => this.handleError('System error retrieving page help content', error));
      }
    }

    private updateForm(htmlPageContent : HtmlPageContent) {
        this.htmlPageContent = htmlPageContent;
        this.formComponent.myForm.patchValue((htmlPageContent));
    }

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

            let htmlPageContent : HtmlPageContent = this.formComponent.myForm.value;
            this._htmlContentService.updateHtmlPageContent(htmlPageContent, this.properties.adminToolsAPIURL).subscribe(
                _ => {
                  //this.mode = "preview";
                  UIkit.tab('#html-tab').show(1);
                  UIkit.switcher('#html-tab-content').show(1);
                  this.showLoading = false;
                },
                err => {
                  //this.mode = "edit";
                  UIkit.tab('#html-tab').show(0);
                  UIkit.switcher('#html-tab-content').show(0);
                  this.handleUpdateError('System error updating page content', err);
                }
            );
        } else {
            //this.mode = "edit";
            UIkit.tab('#html-tab').show(0);
            UIkit.switcher('#html-tab-content').show(0);
            this.errorMessage = "Please fill all required fields";
        }
      }
    }

    cancelCustom() {
      this.errorMessage = "";
      this.updateErrorMessage = "";
      this.router.navigate(['/pages'], { queryParams: { "type": "html", "communityId": this.communityPid}});
      //this.location.back();
      //this.router.navigated = false;
      //this.router.navigate( ['/htmlPageContent/edit'], { queryParams: { "communityId": this.communityPid, "pageId": this.pageId } } );
    }
}
