import {Component, OnDestroy, OnInit, ViewChild} from '@angular/core';
import {ActivatedRoute, Router} from '@angular/router';
import {EmailService} from '../openaireLibrary/utils/email/email.service';
import {Email} from '../openaireLibrary/utils/email/email';
import {EnvProperties} from '../openaireLibrary/utils/properties/env-properties';
import {Composer} from '../openaireLibrary/utils/email/composer';
import {Meta, Title} from '@angular/platform-browser';
import {HelperFunctions} from '../openaireLibrary/utils/HelperFunctions.class';
import {FormBuilder, FormGroup, Validators} from '@angular/forms';
import {properties} from '../../environments/environment';
import {FAQ} from "../openaireLibrary/utils/entities/FAQ";
import {Breadcrumb} from "../openaireLibrary/utils/breadcrumbs/breadcrumbs.component";
import {Subscription} from 'rxjs';
import {PiwikService} from '../openaireLibrary/utils/piwik/piwik.service';
import {SEOService} from '../openaireLibrary/sharedComponents/SEO/SEO.service';

@Component({
  selector: 'contact',
  templateUrl: './contact.component.html',
  styleUrls: ['contact.component.css']
})

export class ContactComponent implements OnInit, OnDestroy {
  public showLoading = true;
  public errorMessage = '';
  public email: Email;
  public faqs: FAQ[] = [];
  public properties: EnvProperties = properties;
  subs: Subscription[] = [];
  description = "Do you have questions? Contact us";
  title = "OpenAIRE - Research Graph | Support";
  public contactForm: FormGroup;
  @ViewChild('AlertModal') modal;

  public breadcrumbs: Breadcrumb[] = [
    {
      name: 'home',
      route: '/'
    },
    {
      name: 'support'
    }
  ];

  constructor(private router: Router,
              private route: ActivatedRoute,
              private emailService: EmailService,
              private _title: Title,
              private _piwikService:PiwikService,
              private _meta: Meta,  private seoService: SEOService,
              private fb: FormBuilder) {
    this.setFaqs();
  }
  
  ngOnInit() {
    this._title.setTitle(this.title);
    this._meta.updateTag({content:this.description},"name='description'");
    this._meta.updateTag({content:this.description},"property='og:description'");
    this._meta.updateTag({content:this.title},"property='og:title'");
    this.email = {body: '', subject: '', recipients: []};
    this.reset();
    this.showLoading = false;
    var url = this.properties.domain + this.properties.baseLink+this.router.url;
    this.seoService.createLinkForCanonicalURL(url, false);
    this._meta.updateTag({content:url},"property='og:url'");
    if(this.properties.enablePiwikTrack && (typeof document !== 'undefined')){
      this.subs.push(this._piwikService.trackView(this.properties, this.title).subscribe());
    }
  }
  
  public send(event) {
    HelperFunctions.scroll();
    if (event.valid === true) {
      this.sendMail(this.properties.admins);
    } else {
      this.errorMessage = 'Please fill in all the required fields!';
    }
  }
  
  public reset() {
    this.contactForm = this.fb.group({
      name: this.fb.control('', Validators.required),
      email: this.fb.control('', [Validators.required, Validators.email]),
      affiliation: this.fb.control('', Validators.required),
      organization: this.fb.control('', Validators.required),
      description: this.fb.control('', Validators.required),
      recaptcha: this.fb.control('', Validators.required),
    });
    this.errorMessage = '';
  }
  
  private sendMail(admins: any) {
    this.showLoading = true;
    this.subs.push(this.emailService.contact(this.properties,
      Composer.composeEmailForGraph(this.contactForm.value, admins),
      this.contactForm.value.recaptcha).subscribe(
      res => {
        this.showLoading = false;
        if (res) {
          this.reset();
          this.modalOpen();
        } else {
          this.errorMessage = 'Email sent failed! Please try again.';
          this.contactForm.get('recaptcha').setValue('');
        }
      },
      error => {
        this.handleError('Email sent failed! Please try again.', error);
        this.showLoading = false;
        this.contactForm.get('recaptcha').setValue('');
      }
    ));
  }
  
  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) {
    this.errorMessage = message;
    console.log('Server responded: ' + error);
    this.showLoading = false;
  }
  
  public goToHome() {
    this.router.navigate(['/']);
  }

  private setFaqs() {
    this.faqs.push({
      "question": "What are \"trusted\" sources?",
      "answer": "OpenAIRE data sources are considered \"trusted\" when researchers rely on them to share, discover, monitor, and assess their scientific products. " +
        "Known sources collected by OpenAIRE are institutional repositories (e.g. university archives, libraries), catch-all repositories (e.g. Zenodo, Figshare, Dryad, B2Share, etc.), " +
        "data repositories (e.g. Pangaea, GESIS, bio sources), thematic repositories (e.g. ArXiv, EuropePMC, RePec, etc.), " +
        "Open Access publishers (e.g. F1000, OpenEdition, etc.), knowledge graphs (e.g. Microsoft Academic Graph, OpenCitations), " +
        "registries (e.g. CrossRef, DataCite, ORCID, GRID.ac, OpenDOAR, re3data.org, etc), aggregators " +
        "(e.g. Unpaywall, BASE, Scielo, DOAJ, CORE-UK, etc.), funders (e.g. European Commission, NSF, Wellcome Trust, etc.)."
    });

    this.faqs.push({
      "question": "What do you mean with “transparent graph”?",
      "answer": "The OpenAIRE Research Graph is transparent because it keeps tracks of the provenance of each and every information it contains. " +
        "For each field you can know if they have been collected from one of our sources, if it has been inferred (and with which algorithm and with which confidence level)"
    });
  }
  
  public ngOnDestroy() {
    this.subs.forEach(sub => {
      if(sub instanceof Subscription) {
        sub.unsubscribe();
      }
    });
  }
}
