import { Component, OnInit, Input, Output, EventEmitter, ViewEncapsulation, ViewChild, ElementRef, AfterViewInit, OnDestroy, OnChanges } from '@angular/core';
import { BISIntentService } from '../bis-services/bis-intent.service';
import { NgForm, FormControl, FormGroup } from '@angular/forms';
import { Subscription } from 'rxjs';

@Component({
  selector: 'bis-invocation-layout',
  templateUrl: './bis-invocation-layout.component.html',
  styleUrls: ['./bis-invocation-layout.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class BISInvocationLayoutComponent implements OnInit,OnChanges, OnDestroy, AfterViewInit {
  
  @ViewChild('invokeForm', { read: ElementRef, static: true }) formElement : ElementRef | any; 
  //Added by Prasad on 07/08/19 [to set dynamic height to bis-messages content]
  @ViewChild('invokeInputContainer', { read: ElementRef }) invokeInputContainer : ElementRef | any;
  
  formGroup : FormGroup | any;

  @Input() intent : any;
  @Output() invoked = new EventEmitter<any>();
  @Output() canceled = new EventEmitter<any>();
  @Output() entered = new EventEmitter<any>();
  //Added by Pratheek on 18-06-19[ using the @Input decorator to get id values so to differentiate the Welcome screen and Quick Action Pamel]-Start
  @Input() targetId: String | any;
  @Input("parentId") assistantId: String | any;
  //Added by Pratheek on 18-06-19[ using the @Input decorator to get id values so to differentiate the Welcome screen and Quick Action Pamel]-End
  //By Sainath T. on 31/12/2018 [To change input date display format]
  constructor(public intentService : BISIntentService) { }

  invocationTemplate : string | any;
  invocationResult : string | any;
  invokeIntentSubmit : Subscription | any;

  ngOnInit() {
    //commented by Pooja S on 31-July-2019 [on the did you mean suggestion]
    /*this.formGroup = new FormGroup({});
    this.intentService.setFormGroup(this.formGroup);
    this.intentService.setFormElement(this.formElement);
    //console.log('BISInvocationLayoutComponent intent', this.intent);
    var spacesText = `&nbsp;&nbsp;&nbsp;`;
    //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-START
    this.invocationTemplate = spacesText + this.intentService.getInvocationTemplate(this.assistantId,this.targetId,this.intent);
    //window["onIntentCancel"] = this.onCancel.bind(this);
    console.log('TargetID 38!!!! ['+this.targetId+'] this.assistantID ['+this.assistantId+']')
    this.invokeIntentSubmit = this.intentService.onInvokeIntentSubmit(this.targetId).subscribe(toSubmit => {
      //console.log('onInvokeIntentSubmit >> toSubmit', toSubmit);
      if ( toSubmit ) {
        this.onSend(toSubmit);
      }
    });*/
  }

  onCancel() {
    this.canceled.emit();
  }

  onSend( toSubmit : boolean )
  {
    //console.log('controls', this.formGroup);
    //var inputs = formGroup.getElementsByTagName("INPUT");
    if( toSubmit ) 
    {
      this.entered.emit();
    }
    if( this.formGroup.valid )
    {
      this.formatInvocationResult();
      this.invoked.emit( this.invocationResult );
    }
    else
    {
      this.intentService.focusInvalidInput();
    }
  }

  formatInvocationResult()
  {
    var invocString = this.intent.INVOC_STRING;
    var formValues = this.formGroup.value;
    //formValues.BIS_INTENT_ID = this.intent.BIS_INTENT_ID;
    console.log('invocString > ', invocString, 'formValues > ', JSON.stringify( formValues ) );
    if( formValues ) {
      for(let controlName of Object.keys(formValues) ) {
        var inputvalue = formValues['INVOKE_' + controlName];
        //Added by Sainath T on 24/10/18[To pass invoke input empty if null]-START
        var value = "";
        if( inputvalue == null || inputvalue == undefined  || inputvalue == "undefined" || inputvalue =="null" )
        {
          value = "";
        }
        else
        {
 		  //By Sainath T. on 31/12/2018 [To change input date display format] -START
          if( typeof( inputvalue ) == 'object' )
          {
            inputvalue = this.intentService.formatDate(inputvalue);
          }
 		  //By Sainath T. on 31/12/2018 [To change input date display format] -END
          value = inputvalue;
        }
        invocString = invocString.replace(new RegExp(':'+controlName, 'g'), ' <u>' + value + '</u> ');
        //Added by Sainath T on 24/10/18[To pass invoke input empty if null]-END
      }
      this.invocationResult = invocString;
    }
  }
  
  //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
  ngOnChanges()
  {
    this.invocationTemplate = "";
    this.formGroup = new FormGroup({});
    this.intentService.setFormGroup(this.formGroup);
    this.intentService.setFormElement(this.formElement);
    var spacesText = `&nbsp;&nbsp;&nbsp;`;
    //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-START
    this.invocationTemplate = spacesText + this.intentService.getInvocationTemplate(this.assistantId,this.targetId,this.intent);
    //this.invocationTemplate1[this.intent.BIS_INTENT_ID] = this.invocationTemplate;
    this.invokeIntentSubmit = this.intentService.onInvokeIntentSubmit(this.targetId).subscribe(toSubmit => {
      //console.log('onInvokeIntentSubmit >> toSubmit', toSubmit);
      if ( toSubmit ) {
        this.onSend(toSubmit);
      }
    });

    var intentInputContainerEle = document.getElementById('intent-input-container');
    console.log( 'ngOnChanges :: intentInputContainerEle : ', intentInputContainerEle );
    if ( intentInputContainerEle )
    {
      console.log('intentInputContainerHeight : ', intentInputContainerHeight);
      var rootElem = <HTMLElement>document.querySelector(':root')
  
      //By Sainath T. on 14-SEP-2019 [To resolve scroll related issue] - Start
      var bisHeaderEle = document.getElementById("bis_showHeader");
      var loadDisplay = false;
      if ( bisHeaderEle )
      {
        loadDisplay = (window.getComputedStyle(bisHeaderEle, null).getPropertyValue("display") == 'none') ? false : true;
        console.log('bisHeader display style',loadDisplay);
      }
      var intentInputContainerHeight: any = ( this.intentService.callFromProteusVision && loadDisplay )? intentInputContainerEle.offsetHeight + 30 : intentInputContainerEle.offsetHeight;
      rootElem.style.setProperty('--invokeInputContainerHeight', intentInputContainerHeight + "px" );
      //By Sainath T. on 14-SEP-2019 [To resolve scroll related issue] - End
    }
  }
  //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] End
  
  ngAfterViewInit() 
  {
    //Added by Prasad on 07/08/19 [to set dynamic height to bis-messages content] START
    console.log( 'BISInvocationLayoutComponent : ngAfterViewInit' );
    if ( this.invokeInputContainer && this.intentService )
    {
      var intentInputContainerEleHeight = this.invokeInputContainer.nativeElement.offsetHeight;
      console.log( 'this.invokeInputContainer', intentInputContainerEleHeight );
      this.intentService.changeInvokeInputContainerHeight( intentInputContainerEleHeight );
    }
    //Added by Prasad on 07/08/19 [to set dynamic height to bis-messages content] END
    var inputElems = this.formElement!.nativeElement!.elements;
    //console.log( 'BISInvocationLayoutComponent : ngAfterViewInit : ', inputElems );
    if( inputElems ) 
    {
      for( var i = 0; i < inputElems.length; i++ )
      {
        if( inputElems.item(i)!.type == 'text' )
          {
            inputElems.item(i)!.focus();
            return;
          }
      }
    }
  }

  ngOnDestroy() 
  {
    console.log( 'BISInvocationLayoutComponent : ngOnDestroy' );
    if ( this.invokeIntentSubmit ) {
      //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-START
      this.intentService.setInvokeIntentSubmit(this.targetId,false);
      //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-End
      this.invokeIntentSubmit.unsubscribe();
    }
	  //Added by Prasad on 07/08/19 [to set dynamic height to bis-messages content] START
    if ( this.invokeInputContainer && this.intentService )
    {
      console.log( 'this.invokeInputContainer', this.invokeInputContainer.nativeElement.offsetHeight );
      this.intentService.changeInvokeInputContainerHeight( 50 );
    }
    //Added by Prasad on 07/08/19 [to set dynamic height to bis-messages content] END
  }
}
