/**
 * Created by stefania on 7/13/17.
 */
import { Component, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from "@angular/router";
import { PageContentFormComponent } from "./page-help-content-form.component";
import { PageHelpContent } from "../../domain/page-help-content";
import { HelpContentService } from "../../services/help-content.service";
import { EnvProperties } from '../../openaireLibrary/utils/properties/env-properties';

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

export class NewPageHelpContentComponent {

    @ViewChild(PageContentFormComponent)
    public formComponent : PageContentFormComponent;

    private errorMessage : string = null;

    private communityPid: string;

    private pageId: string;
    public properties:EnvProperties = null;

    constructor(
        private route: ActivatedRoute,
        private router: Router,
        private _helpContentService: HelpContentService) {}

    ngOnInit() {
      this.route.data
        .subscribe((data: { envSpecific: EnvProperties }) => {
           this.properties = data.envSpecific;
           this.route.queryParams.subscribe(params => {
             this.communityPid = params['community'];
             this.pageId = params['pageId'];
           });
      });
    }

    private saveCustom() {

        this.errorMessage = null;

        if(this.formComponent.myForm.valid) {
            let pageHelpContent : PageHelpContent = this.formComponent.myForm.value;

            this._helpContentService.savePageHelpContent(pageHelpContent, this.properties.adminToolsAPIURL).subscribe(
                _ => {
                  if(this.pageId) {
                    this.router.navigate( ['/pageContents/'], { queryParams: { "community": this.communityPid, "page": this.pageId  } } );
                  } else {
                    this.router.navigate(['/pageContents']);
                  }
                },
                err => this.handleError('System error saving page content', err)
            );
        } else {
            this.errorMessage = "Please fill all required fields";
        }
    }

    private cancelCustom() {
      if(this.pageId) {
        this.router.navigate( ['/pageContents/'], { queryParams: { "community": this.communityPid, "page": this.pageId  } } );
      } else {
        this.router.navigate(['/pageContents']);
      }
    }

    handleError(message: string, error) {
        this.errorMessage = message + ' (Server responded: ' + error + ')';

    }
}
