import React, { forwardRef, useCallback, useEffect, useId, useState } from 'react';
import { IRecord } from '@/queries/records.interfaces';

interface IProps {
  options?: any;
  session: string;
  devIDNO?: string;
  channel?: string;

  record?: IRecord;
  type?: 'stream' | 'record';
}

const Cmsv6Player = typeof window === 'undefined' ? undefined : (window as any).Cmsv6Player;

const Video = forwardRef<any, IProps>(
  ({ session, devIDNO, channel, record, type = 'stream' }, outVideoRef) => {
    const videoRef = React.useRef<HTMLDivElement>(null);
    const swfobjectRef = React.useRef<any>(null);
    

    const id = useId();

    const playVideo = useCallback(() => {
      const swfobject = swfobjectRef.current;
      if (typeof swfobject == 'undefined') {
        return;
      }

      const index = 0;
      if (type === 'stream') {
        swfobject.startVideo(index, session, devIDNO, channel, '1', true);
      }

      if (type === 'record') {
        swfobject.startVod(0, record?.PlaybackUrlWs);
      }
    }, [type, channel, devIDNO, session, record]);

    useEffect(() => {
      console.log('new start');

      const swfobject = swfobjectRef.current;
      if (typeof swfobject == 'undefined') {
        return;
      }

      if (type === 'record') {
        swfobject?.startVod?.(0, record?.PlaybackUrlWs);
      }
    }, [type, record?.PlaybackUrlWs]);

    const initFlash = useCallback(() => {
      const swfobject = swfobjectRef.current;
      if (typeof swfobject == 'undefined') {
        return;
      }

      // First create all windows
      swfobject.setWindowNum(1);
      // Set server information

      var serverHost = window.location.host;
      swfobject.setServerInfo(serverHost.split(':')[0], serverHost.split(':')[1] || '80');

      playVideo();
    }, [playVideo]);

    const initPlayer = useCallback(() => {
      if (swfobjectRef.current) {
        initFlash();
        return;
      }

      // Video plugin width
      var width = '100%';
      // Video plugin height
      var hieght = '100%';

      var options = {
        domId: id,
        isVodMode: true,
        width: width,
        height: hieght,
        lang: 'en',
      };
      swfobjectRef.current = new Cmsv6Player(options);
      if(outVideoRef) {
        (outVideoRef as any).current = swfobjectRef.current
      }
      initFlash();
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [initFlash, id]);

    React.useEffect(() => {
      initPlayer();
    }, []);

    return (
      <div className='h-full w-full pointer-events-none'>
        <div className='h-full w-full' ref={videoRef} id={id} />
      </div>
    );
  },
);

export default React.memo(Video);
