import { useCallback, useEffect, useRef, useState } from 'react';
import { skip } from 'rxjs/operators';
import { Event } from '../../services/event.service';

const PageObs = new Event<any>({
   name: 'initial',
   data: {},
});

export function setSharedData(name: string, data?: any): any {
   PageObs.set({
      name,
      data,
   });
}

type useSharedDataResponse<T> = [(fn: (value: T) => void) => any, (value: T | any, name?: string) => void];

export function useSharedData<T>(nameData: string, d?: any): useSharedDataResponse<T> {
   const onChangeFn = useRef<(value: T) => void>();

   function onChange(fn: (value: T) => void): void {
      onChangeFn.current = fn;
   }

   function setValue<T>(value: any, name?: string): void {
      setSharedData(name ?? nameData, value);
   }

   useEffect(() => {
      const obs = PageObs.observable.pipe(skip(1)).subscribe((value) => {
         if (nameData === value.name) {
            if (onChangeFn.current) onChangeFn.current(value.data);
         }
      });

      return () => {
         obs.unsubscribe();
      };
   }, []);

   return [onChange, setValue];
}
