import { IProps } from "@/common/Iprops.interface"
import { AppContianer } from "@/layouts/AppContianer"
import { PageLayout } from "@/layouts/PageLayout"
import { useEffect, useRef, useState } from "react"
import { useParams } from "react-router"
import {of,fromEvent,filter, map} from 'rxjs'

interface DocViewerType extends IProps{}

export const DocViewer = (props:DocViewerType)=>{
    const params = useParams()
    const url =params['id']=== "1"? import.meta.env.VITE_BAAS33_DOC: import.meta.env.VITE_CHAIN33_DOC
    const viewer = useRef<HTMLIFrameElement>(null)
    const [show,setShow] = useState(false)
    const [height,setHeight] = useState(0)
    useEffect(()=>{
        const target = viewer.current as HTMLIFrameElement
        const Ob = fromEvent<MessageEvent>(window,'message')
        .pipe(filter((messageEvent: MessageEvent) => messageEvent.origin === url),map((msg:MessageEvent)=>msg.data))
        const sub = Ob.subscribe((v)=>{
            setHeight(v.height+200) 
        })
        return(()=>{
            sub.remove(sub)
        })
    },[])
    const test =(e:any)=>{
        const target = document.querySelector('#iframe') as HTMLIFrameElement
        if(target){
            setShow(true)
        }
    }

    return(
        <PageLayout className='h-auto'>
            <div>
                <div className={show?'visible px-[120px] pt-8 h-auto  relative':' invisible'}>
                    <iframe 
                    src={url}
                    id='iframe'
                    scrolling="no"
                    className='w-full overflow-y-hidden h-full'
                    style={{height:height}}
                    onLoad={(e)=>test(e)}
                    ref={viewer}></iframe> 
                </div>

                {
                  show?'':<div className='text-center'>Loading...</div>  
                }
          
            </div>
        </PageLayout>
    )
}