import { Component, OnInit, AfterViewInit, Input, Output, Directive, EventEmitter } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { Injector } from '@angular/core';

declare const $: any;

import { <%-SchemaName%>EditCustComponent } from '../../../<%-moduleName%>-cust/base/<%-schemaName%>/<%-schemaName%>-edit.cust.component';
import { ViewType } from '../<%-schemaName%>.component';
import { <%-SchemaName%>Service } from '../<%-schemaName%>.service';
<%for (let mapField of mapFieldsRef) {%>
import { <%-mapField[1]%> } from '../../<%-mapField[0]%>/<%-mapField[0]%>.service';<% } %>

<%if (schemaHasValidator) {%>
import { NG_VALIDATORS, Validator, ValidationErrors, AbstractControl, FormGroup } from '@angular/forms';
  <%_ compositeEditView.forEach( (field) => {
if (field.validators) {%>
@Directive({
  selector: '[<%-moduleName%><%-SchemaName%>Directive<%-field.FieldName%>]',
  providers: [{provide: NG_VALIDATORS, useExisting: <%-ModuleName%><%-SchemaName%>Directive<%-field.FieldName%>, multi: true}]
})
export class <%-ModuleName%><%-SchemaName%>Directive<%-field.FieldName%> implements Validator {
  validators:any[] = [
      <%field.validators.forEach( (v)=>{%>
         {validator: <%-v.validator%>,
          msg: `<%-v.msg%>`
         },<%})%>
  ];
  validate(control: AbstractControl): ValidationErrors | null {
    //TODO: For validator of NgModelGroup, need to get list of contained controls and do validation on the combined data.

    let value = control.value;
    return this.validateValue(value);
  }
  validateValue(value:any): ValidationErrors | null {
    //only compare when input presents
    let result = true;
    if (typeof value == '<%-field.jstype%>') {
        for (let idx = 0; idx < this.validators.length; idx ++) {
            let obj = this.validators[idx];
            try {
                result = obj.validator(value)
                if (result == false ) return { '<%-moduleName%><%-SchemaName%>Directive<%-field.FieldName%>': obj.msg };
            } catch (e) {
                return { '<%-moduleName%><%-SchemaName%>Directive<%-field.FieldName%>': obj.msg };
            }
        }
    }
    return null;
  }
}<%_}}); %><%#comments: end of: forEach %>
<%}%><%#comments: end of: if (schemaHasValidator%>

@Component({
  selector: 'app-<%-schemaName%>-edit',
  templateUrl: './<%-schemaName%>-edit.component.html',
  styleUrls: ['./<%-schemaName%>-edit.component.css']
})
export class <%-SchemaName%>EditComponent extends <%-SchemaName%>EditCustComponent implements OnInit, AfterViewInit {        
    public action: string = '';
    public minDate = {year: (new Date()).getFullYear() - 100, month: 1, day: 1};

    public override view: ViewType = ViewType.EDIT;

    constructor(
      public override <%-schemaName%>Service: <%-SchemaName%>Service,
      public override injector: Injector,
      public override route: ActivatedRoute,
    ) {
      super(<%-schemaName%>Service, injector, route);
<% let theView = compositeEditView; let isEditView = true;%><%- include('schema-construct.component.ts', {theView: compositeEditView, isEditView: true}) %>

      const detail = {};
      this.detail = this.formatDetail(detail);
    }

    override ngOnInit() {
      super.ngOnInit();
      if (this.embedMode == 'create') { // parent ask to create
        this.action='Create';
        this.getDetailData();
      } else {
        let id = this.route.snapshot.paramMap.get('id');
        if (!this.id) this.id = id? id : '';
        if (this.id) {
            this.action='Edit';
            this.populateDetailForAction(this.id, 'edit'); //populate with action as 'edit'
        }
        else {
            this.action='Create';
            let id = this.route.snapshot.queryParamMap.get('cid');
            if (!this.cid) this.cid = id ? id : '';
            if (this.cid) {
                this.populateDetailFromCopy(this.cid);
            } else {
              this.getDetailData();
            }
        }
      }
      // get editHintFields
      this.searchHintFieldValues();
    }

    ngAfterViewInit() {
      // Initialize all tooltips
      $('[data-bs-toggle="tooltip"]').tooltip();
    }

    public override addFieldsRefComponents() {<%if (sFeatures.hasRef) {%>
      <%for (let field of compositeEditBriefView) { 
        if (field.Ref) {%>
        if (this.field<%-field.FieldName%>) {
      this.fieldsRef['<%-field.fieldName%>'] = this.field<%-field.FieldName%>;
        }<%}
        }%>
    <%}%>
    }

    getDetailData() {
      let detail: any = {<%_ createView.forEach( (field) => { 
            let fn = field.fieldName;let fdv = field.defaultValue;
            if ( typeof(fdv) !== 'undefined' && field.type !== 'SchemaDate') {
              /* Schemedate default value is a function, like Now. So sikp it */
              %>
        <%-fn%>: <%-JSON.stringify(fdv)%>,<%_}
          }); %>
      };
      if (this.initData) {
        // Some data fields have been filled already.
        this.action='Add';
        for (let prop of Object.keys(this.initData)) {
            detail[prop] = this.initData[prop];
            if (!this.initDataAllowChange) {
              this.hiddenFields.push(prop);
            }
        }
      }
      this.detail = this.formatDetail(detail);
    }
}
