import {Component, ElementRef, EventEmitter, Input, OnDestroy, OnInit, Output, ViewChild} from '@angular/core';
import {FormGroup} from "@angular/forms";
import {Subscriber} from "rxjs";
import {Background} from "../../utils/background-utils";

declare var UIkit;

@Component({
  selector: 'quick-contact',
  templateUrl: 'quick-contact.component.html',
  styleUrls: ['quick-contact.component.less']
})
export class QuickContactComponent implements OnInit, OnDestroy {
  public quickContactClicked: boolean = false;
  public showDrop: boolean = false;
  @Input()
  public contactForm: FormGroup;
  @Input()
  public images: string[] = [];
  @Input()
  public contact: string = 'contact';
  public backgroundHeader: Background = {class: 'uk-background-primary', dark: true};
  @Input()
  public sending = false;
  @Input()
  public organizationTypes: string[] = [];
  @Output() sendEmitter: EventEmitter<any> = new EventEmitter<any>();
  private subscriptions: any[] = [];
  @ViewChild('drop') drop: ElementRef;
  
  @Input()
  set background(background: Background | string) {
    if(typeof background === 'string') {
      this.backgroundHeader = {class: background, dark: true}
    } else {
      this.backgroundHeader = background;
    }
  }
  
  ngOnInit() {
    if (typeof document !== 'undefined') {
      this.subscriptions.push(UIkit.util.on(document, 'beforehide', '#quick-contact', (event) => {
        if(this.sending) {
          event.preventDefault();
        }
      }));
      this.subscriptions.push(UIkit.util.on(document, 'show', '#quick-contact', (event) => {
        this.showDrop = true;
      }));
      this.subscriptions.push(UIkit.util.on(document, 'hide', '#quick-contact', (event) => {
        this.showDrop = false;
      }));
    }
    if(typeof this.background === 'string' ) {
      this.background = {class: this.background, dark: true};
    }
  }
  
  ngOnDestroy() {
    this.subscriptions.forEach(value => {
      if (value instanceof Subscriber) {
        value.unsubscribe();
      } else if (value instanceof Function) {
        value();
      }
    });
  }
  
  public close() {
    UIkit.drop(this.drop.nativeElement).hide();
  }
  
  public send(event) {
    this.sendEmitter.emit(event);
  }
}
