import {Component, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {EmailService} from "../openaireLibrary/utils/email/email.service";
import {EnvProperties} from "../openaireLibrary/utils/properties/env-properties";
import {Composer} from "../openaireLibrary/utils/email/composer";
import {Meta, Title} from "@angular/platform-browser";
import {PiwikService} from "../openaireLibrary/utils/piwik/piwik.service";
import {HelperService} from "../openaireLibrary/utils/helper/helper.service";
import {SEOService} from "../openaireLibrary/sharedComponents/SEO/SEO.service";
import {UntypedFormBuilder, UntypedFormGroup, Validators} from "@angular/forms";
import {Subscriber} from "rxjs";
import {properties} from "../../environments/environment";
import {Breadcrumb} from "../openaireLibrary/utils/breadcrumbs/breadcrumbs.component";
import {NotificationHandler} from "../openaireLibrary/utils/notification-handler";
import {StringUtils} from "../openaireLibrary/utils/string-utils.class";

@Component({
    selector: 'contact',
    templateUrl: './contact.component.html'
})
export class ContactComponent implements OnInit {
    public url: string = null;
    public pageTitle: string = "OpenAIRE - Monitor | Contact Us";
    public description: string = "OpenAIRE - Monitor . Any Questions? Contact us to learn more";
    public piwiksub: any;
    public sending = false;
    public properties: EnvProperties = properties;
    public pageContents = null;
    public divContents = null;
    public breadcrumbs: Breadcrumb[] = [{name: 'home', route: '/'}, {name: 'Contact us'}];
    public organizationTypes: string[] = [
        'Funding agency', 'University / Research Center',
        'Research Infrastructure', 'Government',
        'Non-profit', 'Industry', 'Other'
    ];
    public contactForm: UntypedFormGroup;
    @ViewChild('modal') modal;
    private subscriptions = [];
    
    constructor(private route: ActivatedRoute,
                private _router: Router,
                private emailService: EmailService,
                private _meta: Meta,
                private _title: Title,
                private seoService: SEOService,
                private _piwikService: PiwikService,
                private fb: UntypedFormBuilder,
                private helper: HelperService) {
    }
    
    ngOnDestroy() {
        this.subscriptions.forEach(subscription => {
            if (subscription instanceof Subscriber) {
                subscription.unsubscribe();
            }
        });
    }
    
    ngOnInit() {
        this.subscriptions.push(this._piwikService.trackView(this.properties, this.pageTitle).subscribe());
        this.url = this.properties.domain + this.properties.baseLink + this._router.url;
        this.seoService.createLinkForCanonicalURL(this.url);
        this.updateUrl(this.url);
        this.updateTitle(this.pageTitle);
        this.updateDescription(this.description);
        this.reset();
        //this.getDivContents();
        // this.getPageContents();
    }

    private getPageContents() {
        this.subscriptions.push(this.helper.getPageHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
            this.pageContents = contents;
        }));
    }

    private getDivContents() {
        this.subscriptions.push(this.helper.getDivHelpContents(this.properties, 'monitor', this._router.url).subscribe(contents => {
            this.divContents = contents;
        }));
    }

    public send(event) {
        if(event.valid === true) {
            this.sendMail(this.properties.admins);
        }
    }

    public reset() {
        this.contactForm = this.fb.group( {
            name: this.fb.control('', Validators.required),
            surname: this.fb.control('', Validators.required),
            email: this.fb.control('', [Validators.required, Validators.email]),
            job: this.fb.control('', Validators.required),
            organization: this.fb.control('', Validators.required),
            organizationType: this.fb.control('', [Validators.required, StringUtils.validatorType(this.organizationTypes)]),
            message: this.fb.control('', Validators.required),
            recaptcha: this.fb.control('', Validators.required),
        });
    }
    
    private sendMail(admins: any) {
        this.sending = true;
        this.subscriptions.push(this.emailService.contact(this.properties,
            Composer.composeEmailForMonitor(this.contactForm.value, admins),
          this.contactForm.value.recaptcha).subscribe(
            res => {
                if (res) {
                    this.sending = false;
                    this.reset();
                    this.modalOpen();
                } else {
                    this.handleError('Email <b>sent failed!</b> Please try again.');
                }
            },
            error => {
                this.handleError('Email <b>sent failed!</b> Please try again.', error);
            }
        ));
    }

    public modalOpen() {
        this.modal.okButton = true;
        this.modal.alertTitle = 'Your request has been successfully submitted';
        this.modal.alertMessage = false;
        this.modal.cancelButton = false;
        this.modal.okButtonLeft = false;
        this.modal.okButtonText = 'OK';
        this.modal.open();
    }

    handleError(message: string, error = null) {
        if(error) {
            console.error(error);
        }
        NotificationHandler.rise(message, 'danger');
        this.sending = false;
        this.contactForm.get('recaptcha').setValue('');
    }

    public goToHome() {
        this._router.navigate(['/']);
    }

    private updateDescription(description: string) {
        this._meta.updateTag({content: description}, "name='description'");
        this._meta.updateTag({content: description}, "property='og:description'");
    }

    private updateTitle(title: string) {
        var _title = ((title.length > 50) ? title.substring(0, 50) : title);
        this._title.setTitle(_title);
        this._meta.updateTag({content: _title}, "property='og:title'");
    }

    private updateUrl(url: string) {
        this._meta.updateTag({content: url}, "property='og:url'");
    }
}
