// noPage
// withHooks
// import Storage from '@react-native-async-storage/async-storage';

import { LibCurl } from 'esoftplay/cache/lib/curl/import';
import { LibObject } from 'esoftplay/cache/lib/object/import';
import useGlobalState from 'esoftplay/global';
import FastStorage from 'esoftplay/mmkv';
import useSafeState from 'esoftplay/state';

import React, { useEffect } from 'react';
import { View } from 'react-native';

export interface EventBlockArgs {

}
export interface EventBlockProps {
  cache?: boolean,
  url: string,
  LoadingView?: any,
  ErrorView?: (error: string) => any,
  render: (data: any, setData?: (d: any) => void) => any
}

FastStorage.removeItem("event/block")
const blockState = useGlobalState({}, { persistKey: 'event/block2', inFastStorage: true, loadOnInit: true })

export default function m(props: EventBlockProps): any {
  const [data, setData] = useSafeState(blockState.get('block-' + props.url))
  const [error, setError] = useSafeState('')

  useEffect(() => {
    new LibCurl(props.url, null, (res, msg) => {
      setData(res)
      if (props.cache && isValidJSON(res)) {
        blockState.set(LibObject.set(blockState.get(), res)('block-' + props.url))
      }
    }, (msg: any) => setError(msg?.message))
  }, [props.url])

  if (error != '') return props.ErrorView ? props.ErrorView(error) : null
  if (!data) return props.LoadingView || <View style={styleId_ZyMPQq} />
  return props.render(data, setData)
}


function isValidJSON(jsonObject: any) {
  try {
    JSON.parse(JSON.stringify(jsonObject));
    return true;
  } catch (e) {
    return false;
  }
}

const styleId_ZyMPQq: any = { margin: 4, borderRadius: 2, flex: 1, padding: 20, backgroundColor: '#f1f2f3' }