import { Component, OnInit, ViewChild } from '@angular/core';
import { NgForm } from '@angular/forms';
import { ActivatedRoute, Params, Router } from '@angular/router';
import { Editor } from 'primeng/editor';
import { OverlayPanel } from 'primeng/overlaypanel';
import { Subscription } from 'rxjs/Subscription';
import { AppService } from '../../app.service';
import { SERVICES } from '../../constants';
import { MessageTemplateModel } from '../../models/messageTemplateModel';
import { PlaceholderOptionsModel } from '../../models/placeholderOptions.model';
import { TemplateTypeModel } from '../../models/templateTypeModel';
import { SaveService } from '../../oneit/services/save.service';
import { UtilsService } from '../../oneit/services/utils.service';
import { BaseComponent } from '../base/base.component';
import { EditMessageTemplateService } from './edit-message-template.service';

@Component({
  selector: 'app-edit-message-template',
  templateUrl: './edit-message-template.component.html'
})
export class EditMessageTemplateComponent extends BaseComponent implements OnInit {

  subscriptions: Array<Subscription> = [];
  @ViewChild('form') form: NgForm;
  @ViewChild('messageContent') messageContentEditor: Editor;
  @ViewChild('contentLinkModal') contentLinkModal: OverlayPanel;
  createdObjs;
  updatedObjs;
  deletedObjs;

  messageTemplate = new MessageTemplateModel();
  messageTemplateTypes: Array<TemplateTypeModel>;
  subjectPlaceholderOptions: Array<PlaceholderOptionsModel>;
  contentPlaceholderOptions: Array<PlaceholderOptionsModel>;
  subjectPlaceholder: PlaceholderOptionsModel;
  contentPlaceholder: PlaceholderOptionsModel;
  contentCursorPoint;
  temporaryMessageContent = '';
  linkText = '';
  showLoader = false;
  editMode = false;

  constructor(
    private router: Router,
    private activatedRoute: ActivatedRoute,
    private utilsService: UtilsService,
    private saveService: SaveService,
    private appService: AppService,
    private editMessageTemplateService: EditMessageTemplateService
  ) {
    super(utilsService);
  }

  ngOnInit(): void {
    this.createdObjs = {};
    this.updatedObjs = {};
    this.deletedObjs = {};
    this.utilsService.resetCounter();
    this.showLoader = true;
    this.getPlaceholderOptions();
    setTimeout(() => {
      this.subscriptions.push(this.appService.getMessageTemplateTypeEnum()
        .subscribe(
          data => {
            this.messageTemplateTypes = data;
            this.subscriptions.push(this.activatedRoute.params
              .subscribe(
                (params: Params) => {
                  if (params.id && params.id !== '0') {
                    this.editMode = true;
                    this.getMessageTemplateByID(params.id);
                  } else {
                    // TODO: Hardcoded for now
                    this.messageTemplate.HiringTeam = this.appService.HiringTeam;
                    if (this.messageTemplateTypes) {
                      this.messageTemplate.TemplateType = this.messageTemplateTypes[0];
                    }
                    this.utilsService.createObject(this.messageTemplate, this.createdObjs);
                    this.setInputListener();
                    this.showLoader = false;
                  }
                }
              ));
          },
          error => {
            this.utilsService.handleError(error);
          }
        )
      );
    }, 0);
  }

  showSaveBtn(): boolean {
    return this.messageTemplate && this.messageTemplate.ObjectID ?
      (this.messageTemplate.HiringTeam === this.appService.HiringTeam) : false;
  }

  showSaveCopyBtn(): boolean {
    return this.messageTemplate && this.messageTemplate.ObjectID ?
      (!!this.messageTemplate.HiringTeam) : false;
  }

  setInputListener(): void {
    let editElement;
    setTimeout(() => {

      if (this.emailTemplateType()) {
        editElement = this.messageContentEditor.getQuill().container;

        if (editElement) {
          ['keyup', 'click'].forEach(event => {
            editElement.addEventListener(event, () => {
              this.contentCursorPoint = this.messageContentEditor.getQuill()
                .getSelection().index;
            });
          });
        }

      } else {

        if (editElement) {
          editElement = document.getElementById('messageContentTxtAreaId');
          ['keyup', 'click'].forEach(event => {
            editElement.addEventListener(event, () => {
              this.contentCursorPoint = this.getCursorPos(editElement);
            });
          });
        }

      }

    }, 0);
  }

  addAnchorText(show: boolean): void {
    if (show) {
      const delta = {
        ops: [
          {retain: this.contentCursorPoint},
          {insert: this.contentPlaceholder.Placeholder, attributes: {link: this.linkText}}
        ]
      };
      this.messageContentEditor.getQuill()
        .updateContents(delta);
    } else {
      this.linkText = '';
    }
  }

  addPlaceholderInMessageContent($event): void {

    if (typeof this.contentCursorPoint === 'number') {

      if (this.emailTemplateType()) {
        if (this.contentPlaceholder.IsLink) {
          this.contentLinkModal.toggle($event);
        } else {
          this.messageContentEditor.getQuill()
            .insertText(this.contentCursorPoint, this.contentPlaceholder.Placeholder);
        }
      } else {
        const textarea: HTMLTextAreaElement = document.getElementById('messageContentTxtAreaId') as HTMLTextAreaElement;
        this.setValueAndFocus(textarea, 'messageContentTxtArea', this.contentPlaceholder.Placeholder);
      }

    }

  }

  showPlainText(HTMLTitle: string): string {
    const temp = document.getElementById('showPlainText');
    temp.innerHTML = HTMLTitle;
    const title = temp.innerText.trim();
    temp.innerHTML = '';

    return title;
  }

  storeMessageContent(): void {

    if (this.messageTemplate.MessageContent !== undefined) {

      if (this.messageTemplate.TemplateType.Description === 'SMS') {
        this.temporaryMessageContent = this.messageTemplate.MessageContent;
        this.messageTemplate.MessageContent = this.showPlainText(this.temporaryMessageContent);
      } else {
        this.messageTemplate.MessageContent = this.temporaryMessageContent !== '' ? this.temporaryMessageContent
          : this.messageTemplate.MessageContent;
      }

    }

  }

  addPlaceholderInSubject(): void {
    if (this.emailTemplateType()) {
      const input: HTMLInputElement = document.getElementById('subjectInputId') as HTMLInputElement;
      this.setValueAndFocus(input, 'subjectInput', this.subjectPlaceholder.Placeholder);
    }
  }

  getCursorPos(input): number {
    if ('selectionStart' in input && document.activeElement === input) {
      return input.selectionStart;
    }

    return -1;
  }

  getMessageTemplateByID(id): void {

    this.showLoader = true;
    this.createdObjs = {};
    this.updatedObjs = {};
    this.deletedObjs = {};
    this.utilsService.resetCounter();
    this.utilsService.clearErrorMessages();

    this.subscriptions.push(this.editMessageTemplateService.getMessageTemplateByID(id, [])
      .subscribe(
        data => {
          this.messageTemplate = data;
          this.updatedObjs[this.messageTemplate.ObjectID] = this.messageTemplate;
          this.showLoader = false;
          setTimeout(() => this.setInputListener(), 0);
        },
        error => {
          this.showLoader = false;
          this.utilsService.handleError(error);
        }
      )
    );
  }

  saveMessageTemplate(saveCopy = false): void {
    this.utilsService.clearErrorMessages();
    const service = `svc/${saveCopy ? SERVICES.SAVE_MESSAGE_AS_COPY : SERVICES.SAVE}`;

    if (this.form.invalid) {
      this.utilsService.showAllErrorMessages();
    } else {
      this.showLoader = true;
      this.subscriptions.push(this.saveService.saveObjects(service, this.createdObjs, this.updatedObjs, this.deletedObjs)
        .subscribe(
          () => {
            this.utilsService.handleSuccess();
            this.router.navigate(['/list-message-template']);
          },
          error => {
            this.showLoader = false;
            this.utilsService.handleError(error);
          }
        )
      );
    }
  }

  getPlaceholderOptions(): void {
    this.subscriptions.push(this.appService.getPlaceholderOptionsEnum()
      .subscribe(options => {
        this.contentPlaceholderOptions = options.filter(option => option.ShowForContent);
        this.subjectPlaceholderOptions = options.filter(option => option.ShowForSubject);
      })
    );
  }

  emailTemplateType(): boolean {
    return this.messageTemplate && this.messageTemplate.TemplateType ?
      this.messageTemplate.TemplateType.Value === 'EMAIL' :
      false;
  }

  smsTemplateType(): boolean {
    return this.messageTemplate && this.messageTemplate.TemplateType ?
      this.messageTemplate.TemplateType.Value === 'SMS' :
      false;
  }

  setValueAndFocus(element, elementId, placeholder): void {
    const start = element.selectionStart;
    const end = element.selectionEnd;
    element.value = `${element.value.substring(0, start)}${placeholder}${element.value.substring(end)}`;
    this.focusField(elementId);
    element.selectionEnd = end + placeholder.length;
  }

  focusField(elementId: string): void {
    setTimeout(() => {
      try {
        document.getElementById(`${elementId}Id`)
          .focus();
        document.getElementById(`${elementId}Id`)
          .getElementsByTagName('input')[0]
          .focus();
      } catch (e) {
        // ignore this.
      }
    }, 0);
  }
}
