import { Component, OnInit, ViewChild, ViewEncapsulation, OnDestroy, Input } from '@angular/core';
import { BISIntentService } from '../bis-services/bis-intent.service';
import { BISSelectionListComponent } from '../bis-components';
import { Subscription } from 'rxjs';

@Component({
  selector: 'bis-interaction',
  templateUrl: './bis-interaction.component.html',
  styleUrls: ['./bis-interaction.component.css'],
  encapsulation: ViewEncapsulation.None
})
export class BISInteractionComponent implements OnInit, OnDestroy {

  @ViewChild(BISSelectionListComponent) pophelp: BISSelectionListComponent | any;

  intentSubscription: Subscription | any;
  // userIntents: any[];
  // filteredIntents: any[];
  userIntents: any;
  filteredIntents: any;
  invokeArgSubscription:  | any;
  filteredArgsData: any;
  selectedIntent: any;
  @Input() intentInput: string | any;//To detect changes
  //Added by Prasad on 19/10/18  [to handle fallback response]
  fallbackIntentSubscription: Subscription | any;
  fallbackIntent: any;
  //For Speech Recognition - Start
  listenAnimation: boolean = false;
  stopAnimation: boolean = false;
  placeholder: string = 'Ask something...';
  isIntentInputProtected: boolean = false;
  isBrowser: boolean = false;
  stopListnFlag: boolean = true;
  //Added by sadique shaikh on 9-07-2019[Add variable user pref Value]
  prefValue:string | any;
  //Changes by Pratheek on 18-06-19[ getting the value of id to differentiate the Welcome screenn and Quick Action Panel]-Start
  @Input("parentId") assistantID : string | any;
  @Input("substrictionVal") targetId: string | any;
  //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
  didYouMeanIntents: any = [];
  callFromProteusVision: boolean | any;
  //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] End
  //Changes by Pratheek on 18-06-19[ getting the value of id to differentiate the Welcome screenn and Quick Action Panel]-End
  //For Speech Recognition - End
 
  constructor(public intentService: BISIntentService) { } 
  ngOnInit() {
    this.isBrowser = this.intentService.isBrowser;
    //Added by Sainth T. on 09-SEP-2019 [To identify the app and set the Css]
    this.callFromProteusVision = this.intentService.callFromProteusVision;
    console.log('BISInteractionComponent ngOnInit',this.isBrowser);
    //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-START
    this.intentSubscription = this.intentService.getIntents(this.targetId).subscribe(intents => {
      if (intents instanceof Array) {
        //console.log('BISInteractionComponent ngOnInit getIntents subscribe', intents);
        this.userIntents = this.intentService.filterUserIntents(intents);
        //console.log('BISInteractionComponent...ngOnInit ', this.userIntents);
      }
    }); 
    //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-START
    this.invokeArgSubscription = this.intentService.getInvokeArgSuggestion(this.targetId).subscribe(filteredArgsData => {
      //console.log('invokeArgSubscription filteredInvokeArgs', filteredArgsData);
      this.filteredArgsData = filteredArgsData;
      //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
      if(this.filteredArgsData.values && this.filteredArgsData.values.length > 0)
      {
        this.didYouMeanIntents = null;
      }
      //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] End
    });
    //Added by Prasad on 19/10/18  [to handle fallback response] START
	//Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-START
    this.fallbackIntentSubscription = this.intentService.handleFallbackIntents(this.targetId).subscribe(fallbackIntent => {
      this.fallbackIntent = fallbackIntent;
      console.log('fallbackIntent', fallbackIntent);
   	  //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
      if( fallbackIntent instanceof Array )
      {
        this.didYouMeanIntents = this.intentService.filterIntents( fallbackIntent, this.userIntents );
        console.log('didYouMeanIntents', this.didYouMeanIntents );
      }
      else
      {
        this.handleFallbackIntent(this.fallbackIntent);
      }
      //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] End
    });
    //Added by Prasad on 19/10/18  [to handle fallback response] END
    //Added by Pratheek on 18-06-19[ call the refresh method so to get the updated data]-START
    this.intentService.ngRefresh();
	//Added by Pratheek on 18-06-19[  call the refresh method so to get the updated data]-End
  }
  //Added by Prasad on 19/10/18  [to handle fallback response] START
  handleFallbackIntent(value: string) 
  {
    if (value && value.trim().length > 0) 
    {
      const filterValue = value.toLowerCase();
      //Added optional parameter true to filter fallback intent with diff. condition 
      this.filteredIntents = this.intentService.filterIntents(filterValue, this.userIntents, true);
      if (this.filteredIntents && this.filteredIntents.length > 0) 
      {
        var selectedIntent = this.filteredIntents[0];
        this.onSelectIntent(selectedIntent);
        this.filteredIntents = null;
        //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
        this.didYouMeanIntents = null;
      }
    }
  }
  //Added by Prasad on 19/10/18  [to handle fallback response] END
  //Added by sadique shaikh 10/07/2019[prevfvalue arguement pass to setPref value]
  filterIntents(value: string, prefValue:string) 
  {
    this.prefValue = prefValue;
    // Abhishek T, Storing user input text
    this.intentInput = value;
    //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
    this.didYouMeanIntents = null;
	  //Added by sadique shaikh 19/07/2019[For Word search]
    //Changed by Pooja S on 31-July-2019 [on the did you mean suggestion] 
    //Changed by Amey W. [To search intent with % ] on 02-07-2019
    //Changed by Amey W. [To resolved he issue while searching the intent ] on 27-08-2019
    if( value && ( ( value.trim().length > 0 && value.charAt(0) != '%') || ( prefValue == 'speech' && value.trim().length > 0 ) || ( value.charAt(0) == '%' && value.trim().length > 1 ) ) ) 
    {
      const filterValue = value.toLowerCase().trim();
      this.filteredIntents = this.intentService.filterIntents(filterValue, this.userIntents);
    }
    else
    {
      this.filteredIntents = [];
    }
  }

  onArgumentEnter() 
  {
    console.log('onArgumentEnter', this.filteredArgsData);
    if (this.filteredArgsData && this.filteredArgsData.values && this.filteredArgsData.values.length > 0) 
    {
      this.onSelectArgument(this.filteredArgsData.values[0]);
    }
  }

  //On Argument selection from suggestion chips
  onSelectArgument(filterItem: any) {
    var fieldName = this.filteredArgsData.fieldName;
    console.log('onSelectValue >> ', fieldName, ' filterItem : ', filterItem);
    this.intentService.setInputValue(fieldName, filterItem.id, filterItem.value);
    this.filteredArgsData = null;
  }

  // intentInput : 'Enter' key press
  onInvokeEnter() 
  {
    /* //By Sainath T on 27/08/2019
    this.intentService.onIntentSelection(this.targetId,true); */
    
    //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
    this.intentService.setFormGroup(null as any);
    this.intentService.setFormElement(null as any);
    if (this.filteredIntents && this.filteredIntents.length > 0)
    {
      var selectedIntent = this.filteredIntents[0];
      this.onSelectIntent(selectedIntent);
    }
    //No suggestion for intents
    else
    {
      //Changed by Abhishek T on 29-OCT-18 [Added one parameter for passing user input string] START
      this.onInvokeSend(null as any, this.intentInput);
      //Changed by Abhishek T on 29-OCT-18 [Added one parameter for passing user input string] END
    }
  }

  //Call in three ways.
  //1. On intent selection from suggestion chips
  //2. On intent selection from intent pophelp
  //3. On 'Enter' key press from intentInput
  //Added by Sainth T. on [pass parameter to check the call is from intent selection list]
  onSelectIntent(selectedIntent: any, fromSelectionLst?: boolean) 
  {
    console.log('In if onSelectIntent22', selectedIntent, 'fromSelectionLst[', fromSelectionLst, ']');
    if (fromSelectionLst == undefined)
    {
      this.intentService.onIntentSelection(this.targetId,true);
    }

    if (typeof selectedIntent == 'object') 
    {
      this.selectedIntent = selectedIntent;
      this.intentService.ngRefresh();
      //By Sainath T on 27/08/2019
      // if (selectedIntent.INVOC_STRING!.length == 0)
      if ( selectedIntent.INVOC_STRING!.length == 0 || selectedIntent.INVOC_STRING!.indexOf( ":" ) == -1 )
      {
        this.onInvokeSend(selectedIntent.INVOC_DESCR);
      }
    }
    // Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start 
    this.didYouMeanIntents = null;
    this.filteredArgsData = null;
  }

  // Call from invocation-layout and onclick of 'Send' button
  onInvokeSend(invocationResult?: string, inputString?: string) 
  {
    //By Sainath T on 27/08/2019 [To set default height to input container to resolve scroll issue]
    this.intentService.changeInvokeInputContainerHeight( 50 );
    //Added by sadique shaikh on 9-07-2019[Set user pref Value]
    this.intentService.setUserPref(this.prefValue).subscribe(
      resp =>{
        console.log('setUserPref Success!!',resp);
      }
    );

    if (!invocationResult) 
    {
      invocationResult = this.intentInput;
    }
    if (!invocationResult || invocationResult.trim().length == 0) 
    {
      return;
    }
     //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-START
    //console.log('Inside bis-interaction 208!!!!![' + invocationResult+'] inputString ['+inputString+'] this.targetId ['+this.targetId+']');
    this.intentService.addUserMsg(this.targetId,invocationResult);
    //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-End
    var intentId = "";
    if (this.selectedIntent != null) 
    {
      intentId = this.selectedIntent.BIS_INTENT_ID;
    }
    // Changed by Abhishek T on 29-OCT-18 [Send user entered text in request] START
    this.intentService.getIntentResult(intentId, inputString, invocationResult).subscribe(response => {
	  //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-START
      this.intentService.processIntentResponse(response,this.targetId);
	  //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-End
      this.intentService.ngRefresh();
    });

    this.intentInput = '';
    this.selectedIntent = null;
    this.filteredIntents = null;
    //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
    this.didYouMeanIntents = null;
    this.filteredArgsData = null;
    // to reset speech recognition variables
    this.stopAnimation = false;
    this.listenAnimation = false;
    this.isIntentInputProtected = false;
    //Added by Sainath T. on 16-Aug-2019 [to empty received formValueEntities]
    this.intentService.formValueEntities['bi_assistant_'+ this.targetId].next( {} );
    this.placeholder = 'Ask Something...';
    this.intentService.ngRefresh();
  }

  onCancel() 
  {
    //Added by Sainath T. on 16-Aug-2019 [to empty received formValueEntities]
    this.intentService.formValueEntities['bi_assistant_'+ this.targetId].next( {} );
    // this.intentInput = '';
    this.selectedIntent = null;
    // this.filteredIntents = null;
    this.isIntentInputProtected = false;
    this.stopAnimation = false;
    this.listenAnimation = false;
    this.intentService.ngRefresh();
    //Added by Pooja S on 31-July-2019 [on the did you mean suggestion] Start
    this.didYouMeanIntents = null;
    //Added by Prasad on 07/08/19 [to set dynamice height to container] START
    setTimeout( () => {
      var intentInputContainerEle: any = document.getElementById('intent-input-container');
      console.log('BISInteractionComponent :: onCancel : ', intentInputContainerEle.offsetHeight);
      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 = ( 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
      }
    }, 0);
    //Added by Prasad on 07/08/19 [to set dynamice height to container] END
  }

  scrollToBottom() 
  {
    /*var objDiv = document.getElementById("bis-message-list");
    console.log('bis-message-list >> scrollTop : ', objDiv.scrollTop , 'scrollHeight : ', objDiv.scrollHeight);
    objDiv!.scrollTop = objDiv.scrollHeight + 400;*/
    this.intentService.scrollToBottom();
    this.intentService.setMobileHeader();
  }

  showMoreIntents() 
  {
    window.scrollTo(0, 0);
    if (window.top.document.getElementById("MobileContents") != null) 
    {
      // window.top.document.getElementById("MobileContents").scrollTop = 0;
      window.top.document.getElementById("MobileContents")!.scrollTop = 0;
    }
    var userIntents = this.userIntents.filter((userIntent: any) => {
      if (userIntent.INVOC_ORDER == 1) {
        return userIntent;
      }
    });
    //Added by Sainath T. on 14-SEP-2019 [To unset the focus on list click]
    this.intentService.unSetInputFocus();
    this.pophelp.loadIntentPophelp(userIntents);
  }

  ngOnDestroy()
  {
    if (this.intentSubscription) {
      this.intentSubscription.unsubscribe();
    }
    if (this.invokeArgSubscription) {
      this.invokeArgSubscription.unsubscribe();
    }
    //Added by Prasad on 19/10/18  [to handle fallback response] START
    if (this.fallbackIntentSubscription) {
      this.fallbackIntentSubscription.unsubscribe();
    }
    //Added by Prasad on 19/10/18  [to handle fallback response] END
  }

  setIntentInput(result?: string | any) 
  {
    console.log('setIntentInput::[',result,']');
    this.intentInput = result;
    this.intentService.ngRefresh();
    //Added by sadique shaikh on 9-07-2019[Set user pref Value 'speech']
    this.filterIntents(this.intentInput,'speech');
  }

  setListenAnimation(value:boolean){
    console.log('setListenAnimation::[',value,']');
    this.listenAnimation = value;
  }
  setStopAnimation(value:boolean)
  {
    console.log('setStopAnimation::[',value,']');
    this.stopAnimation = value;
  }
  setPlaceholder(value:string)
  {
    console.log('setPlaceholder::[',value,']');
    this.placeholder = value;
  }
  setIntentInputProtected(value:boolean)
  {
    console.log('setIntentInputProtected::[',value,']');
    this.isIntentInputProtected = value;
    //this.intentService.scrollToBottomNFocus(true);
  }
}

