// WDWidgetBase.tsx 
import "./WDWidgetBase.css";
import { Component } from 'react';
import IWDWidgetBaseState from './IWDWidgetBaseState'; 
import IWDWidgetBaseProps from './IWDWidgetBaseProps';
import EventContext from "@widgets/WDWidgetBase/EventContext";
import EventObject from "./EventObject";

export default class WDWidgetBase<P extends IWDWidgetBaseProps, S extends IWDWidgetBaseState> extends Component<P, S>{
  
  static contextType = EventContext;
  context!: React.ContextType<typeof EventContext>;
  protected receiveEvents: boolean = false;
  protected manualInitState: boolean;

  // *************** Utilizzato dal componente PADRE *********************
  handleEvent = (widgetName: string, action: string, data?: any) => {
    if (widgetName !== "" && action !== "") {
      const functionName = `${widgetName}_${action}`;
      const func = (this as any)[functionName] as (data: EventObject) => boolean;
      let retEvent: boolean = true;
      if (func) {
        const eObj: EventObject = {
          name: widgetName,
          action: action,
          data: data
        }
        if (func(eObj) === false) {
          retEvent = false;
        };
        console.log(`Ritorno evento ${functionName} -> ${retEvent}`)
      } else {
        // console.log("Function not found:", functionName);
      }
      // Chiamo la funzione al livello superiore
      if (this.context && retEvent) {
        this.context['ManageEvent']?.(widgetName, action, data);
      }  
    }
  };
  eventHandlers = {
    ManageEvent: this.handleEvent
  };
  // ************** Utilizzato dal componente FIGLIO *********************
  event(action: string, data?: any) {
    if (this.props.name && this.context) {
      this.context['ManageEvent']?.(this.props.name, action, data);
    }
  }
  // *********************************************************************

  constructor(props: P, defaultValue?: any) {
    super(props);
    this.manualInitState = false;
    if (defaultValue && this.props.debug) {
      // Caricamento di STATE con il default value contenuto nel JSON
      this.state = {
        ...this.state,
        ...defaultValue
      }
    } else if (this.props.data) {
      // Caricamento di STATE con l'oggetto DATA valorizzato nei props
      this.state = {
        ...this.state,
        ...this.props.data
      }
    } else {
      this.manualInitState = true;
    }
  }

  renderContent() {
    return <div>Contenuto base predefinito</div>;
  }

  render(){
    return(
      <>
        {this.receiveEvents ? (
          <EventContext.Provider value={this.eventHandlers}>
            {this.renderContent()}
          </EventContext.Provider>
        ) : (
          this.renderContent()
        )}
      </>
    );
  }
}
