import { Component, OnInit, Input, Output, ViewChild, EventEmitter } from '@angular/core';
import { BISIntentService } from '../bis-services/bis-intent.service';
import { BISSelectionListComponent } from './bis-selection-list/bis-selection-list.component';
import { FormControl, FormGroup } from '@angular/forms';

//By Sainath T. on 31/12/2018 [To implement date picker for data_type 'date']-START
import { MatDatepickerInputEvent } from '@angular/material/datepicker';
import { DateAdapter, MAT_DATE_FORMATS } from '@angular/material/core';
import { AppDateAdapter, APP_DATE_FORMATS } from '../../search-menu/date.adapter';
import { DatePipe } from '@angular/common';
@Component({
  selector: 'bis-invoke-input',
  template: `
  <div [ngClass]="dataType.length != 0 && dataType == 'date'?'bis-invoke-input-date':'bis-invoke-input'">
    <span *ngIf="required" class="invoke-input-mandatory">*</span>
      <input type="hidden" 
            [formControl]="hiddenInput" 
            [name]="name" />
            
      <!-- By Sainath T. on 31-12-18 [for date picker implementation]-START -->   
      <ng-container *ngIf="dataType && dataType =='date'; else textField">
        <mat-form-field class = "bis-mat-date">
          <input matInput [matDatepicker]="picker" 
          [formControl]="invokeInput"
          (dateChange)="changeDate($event);" >

          <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
          <mat-datepicker #picker></mat-datepicker>
        </mat-form-field>
      </ng-container>
      <!-- By Sainath T. on 31-12-18 [for date picker implementation]-END -->   

      <ng-template #textField>
        <input class="invoke-input" type="text" 
              [formControl]="invokeInput" 
              [name]="invoke_name"
              [placeholder]="placeholder" 
              [required]="required" 
              autocomplete = "off"
              (keyup) = "getInputSuggestion($event.target.value)"
              (keyup.enter)= "onEnterInvoke()"
              (keydown.f2) = "openSuggest()" />
      </ng-template> 
      <span *ngIf="pophelpConfig">
        <i class="material-icons invoke-suggestion" (click)="openSuggest();" >keyboard_arrow_right</i>
      </span>
    </div>
    <bis-selection-list [parentId]='assistantid' (onSelectionChange)="onSelectionChange($event)" ></bis-selection-list>
  `, 
  styles: [
    `
      .invalid-input {
        background-color: yellow;
      }

      .invoke-input-mandatory {
        color: #ff6a6a;
      }

      .invoke-input{
        border: none;
       /* border-bottom: 1px solid lightgray; */
        line-height: 24px;
        height: 24px;
        width: 105px;
        outline: none;
        padding: 0 0 0 5px;
      }

      .bis-invoke-input {
        display: inline-block;
        position: relative;
        padding: 0 0 0 5px;
        border-bottom: 1px solid lightgray;
        background-color: #fff;
      }
      /*By Sainath T. on 31/12/2018 [To implement date picker for data_type 'date'] - START */
      .bis-invoke-input-date {
        display: inline-block;
        position: relative;
        padding: 0 0 0 5px;
        border-bottom: 0px !important;
        background-color: #fff;
      }
      ::ng-deep .mat-form-field .mat-form-field-underline
      {
        background-color: lightgray !important;
      }
      /*By Sainath T. on 31/12/2018 [To implement date picker for data_type 'date'] -END */
      /* By Sainath T on 27/08/2019 */
      .bis-mat-date{
        width : 120px !important;
      }
      `
  ],
  providers: [
    {
      provide: DateAdapter, useClass: AppDateAdapter
    },
    {
      provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS
    },
    DatePipe
  ]
})
export class BISInvokeInputComponent implements OnInit {

  @ViewChild(BISSelectionListComponent) pophelp : BISSelectionListComponent | any;
  @Input('userintentargkey') userIntentArgKey : string | any;
  //Sainath T. on 23/11/18
  public formGroup : FormGroup | any;
  hiddenInput : FormControl | any;
  name : string = 'input-1';

  invokeInput : FormControl | any;
  invoke_name : string = 'invoke-input-1';
  required : boolean = false;
  placeholder : string = '';
  pophelpConfig : any;

  //By Sainath T. on 31/12/2018 [To implement date picker for data_type 'date'] -END  dataType = "";
  dataType: any = "";

  /*
    ARG_NAME:"ACCT_CODE"
    ARG_SOURCE:"I"
    ARG_VALUE:""
    BIS_ENTITY_DESCR:"Account code"
    DATA_MODEL:"ACCT_CODE_DM"
    DESCR:"Account code"
    MANDATORY_OPT:"1"
    SEL_TYPE:"S"
  */
  invokeArg : any;
  //Added by Pratheek on 18-06-19[ using @Inout decorator to get the values from parent class so to differentiate the Welcome screen and Quick Action Pamel]-Start
  @Input() assistantid : string | any;
  @Input() targetid:string | any
  formValueEntities: any = {};//this we get when AI entity detection fails then we set these values to FormGroup
  //Added by Pratheek on 18-06-19[ using @Inout decorator to get the values from parent class so to differentiate the Welcome screen and Quick Action Pamel]-End
  //By Sainath T. on 31/12/2018 [To implement date picker for data_type 'date']
  constructor(public intentService : BISIntentService) { }

  ngOnInit() 
  {
    this.invokeInput = new FormControl();
    this.hiddenInput = new FormControl();
    this.invokeArg = this.intentService.getInvokeArg(this.userIntentArgKey);
    //Added by Sainath T. on 16-Aug-2019 [If AI entity detection fails]-Start
    let [intentId, argName] = this.userIntentArgKey.split(":");
    this.intentService.getFormValueEntities(this.targetid).subscribe(
     resp => {
       console.log('getFormValueEntities[',resp,']');
       if(resp)
       {
        this.formValueEntities = resp;
       }
      }
    );
	//Added by Sainath T. on 16-Aug-2019 [If AI entity detection fails]-End
    
    this.name = this.invokeArg.ARG_NAME; //"ACCT_CODE"
    this.intentService.addToForm(this.name, this.hiddenInput);

    this.invoke_name = 'INVOKE_' + this.invokeArg.ARG_NAME; //"INVOKE_ACCT_CODE"
    this.intentService.addToForm(this.invoke_name, this.invokeInput);
    
    //By Sainath T. on 03/12/18 [To get FormGroup data]
    this.formGroup = this.intentService.getFormGroup();
    console.log('this.invokeArg.DATA_TYPE>[', this.invokeArg.DATA_TYPE, ']');
    var dataType = this.invokeArg.DATA_TYPE;
    if (dataType != null && dataType != '' && dataType != 'undefined' && dataType.length != 0) {
      this.dataType = dataType.toLowerCase();
    }
    //Added by Sainath T. on 16-Aug-2019 [set if formValueEntities are received]-Start
    if( this.invokeArg.ARG_SOURCE == 'D' || this.formValueEntities) // D - Default Value will be set ARG_VALUE
    {
      //By Sainath T. on 20/03/19 [To get current month when Arg value is 'CUR_MONTH']-Start
      var defValue = "";
      var hiddenDefValue = "";
      if(this.formValueEntities && (intentId == this.formValueEntities['BIS_INTENT_ID']))
      {
        var argValueArr = this.updateFormGroup(this.formValueEntities , this.invokeArg.ARG_NAME);  
        defValue = argValueArr[0];
        hiddenDefValue = argValueArr[1];
      }
      else
      {
        defValue = this.intentService.getDefaultValue(this.invokeArg.ARG_VALUE);
      }
      console.log('default value for [ ',this.invokeArg.ARG_VALUE,']=[',defValue,']');
      if (this.dataType == 'date') {
        this.invokeInput.setValue(this.intentService.getDefaultDateObj(this.invokeArg.ARG_VALUE));
        this.hiddenInput.setValue(defValue);
      } 
      else 
      {
        this.invokeInput.setValue(defValue);
        if(hiddenDefValue && hiddenDefValue.length > 0)
        {
          this.hiddenInput.setValue(hiddenDefValue);
        }
        else
        {
          this.hiddenInput.setValue(defValue);
        }
      }
      //By Sainath T. on 20/03/19 [To get current month when Arg value is 'CUR_MONTH']-End
      //Added by Sainath T. on 16-Aug-2019 [set if formValueEntities are received]-End
    }
    this.placeholder = this.invokeArg.DESCR; //"Account code"
    this.required = this.invokeArg.MANDATORY_OPT == 1; // 1 - true; 0 or empty - false  
    if( this.invokeArg.DATA_MODEL )
    {
      this.pophelpConfig = {};
      this.pophelpConfig.fieldName = this.name;
      this.pophelpConfig.title = this.invokeArg.BIS_ENTITY_DESCR; //"Account code"
      this.pophelpConfig.data_model_name = this.invokeArg.DATA_MODEL; //"ACCT_CODE_DM"
      var multiOpt = this.invokeArg.SEL_TYPE;
      this.pophelpConfig.multi_opt = (multiOpt == 'M') ? '1' : ( (multiOpt == 'S' || multiOpt == '') ? '0' : '-1' ) ; // M - Multi select (1); S or empty - Single select (0)
    }
  	this.getInputSuggestion("dummy");
    //console.log( "pophelpConfig : ", this.pophelpConfig );
  } 

  openSuggest()
  {
    this.pophelpConfig.fieldValue = this.hiddenInput.value;
    //Sainath T. on 03/12/2018 [ to pass form group data to pophelp ]-START
    this.pophelp.loadArgPophelp(this.pophelpConfig, this.formGroup);
  }

  onSelectionChange(data: any)
  {
    this.intentService.setInputValue( this.name, data.value, data.display );
  }

  getInputSuggestion(value: string) 
  {
    if ( "dummy" != value )
    {
      this.hiddenInput.setValue( value );
    }
    if(this.pophelpConfig)
    {
      if( value && value.trim().length > 0 )
      {
        //Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-Start
        this.intentService.filterInputSuggestion(this.targetid,this.pophelpConfig, value);
 		//Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-End
      }
      else
      {
		//Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-Start
        this.intentService.resetInputSuggestion(this.targetid);
		//Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-End
      }
    }
  }

  onEnterInvoke() 
  {
	//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,true);
	//Added by Pratheek on 18-06-19[ passing the id values so to differentiate the Welcome screen and Quick Action Pamel]-Start
  }

  //By Sainath T. on 31/12/2018 [To implement date picker for data_type 'date'] -START
  changeDate( event: MatDatepickerInputEvent<Date> )
  {  
      console.log('selected change date--',event);
      this.invokeInput.setValue(this.invokeInput.value); 
      this.hiddenInput.setValue(this.intentService.formatDate(this.invokeInput.value));
      this.intentService.addToForm(this.invoke_name, this.invokeInput);
      this.intentService.addToForm(this.name, this.hiddenInput);
  }
  //By Sainath T. on 31/12/2018 [To implement date picker for data_type 'date'] -END
  //Added by Sainath T. on 16-Aug-2019 [implement entity value detection if AI fails]-Start
  updateFormGroup(formValueEntities: any, argName: any) {
    var invokArgValue = "";
    var argValue = "";
    var argValueArr: any = [];
    console.log('in update formGroup::', formValueEntities);
    if( formValueEntities["INVOKE_" + argName] != undefined && formValueEntities[ "INVOKE_" + argName] )
    {
      invokArgValue = formValueEntities[ "INVOKE_" + argName ];
    }
    argValueArr.push( invokArgValue );
    if( formValueEntities[ argName ] != undefined && formValueEntities[ argName ] )
    {
      argValue = formValueEntities[ argName ];
    }
    argValueArr.push( argValue ); 
    return argValueArr;
  }
  //Added by Sainath T. on 16-Aug-2019 [implement entity value detection if AI fails]-End

}
