import React, { useEffect, useState } from 'react';
import ScreenDetail from 'containers/screen-detail';
import qs from 'qs';
import http from 'utils/fetch';
import { api } from 'constants/config';

export default function AppDetail() {
  const [enable, setEnable] = useState(false);
  useEffect(() => {
    async function load() {
      const search = window.location.search;
      const token = qs.parse(search.slice(1)).token;
      if (token && typeof token === 'string') {
        const parsedToken = JSON.parse(window.atob(token.split('.')[1]));
        const arr = document.referrer.match(/(http|https):\/\/([\w]+\.)+[\w]+(:[0-9]+)?/) || [];
        if (parsedToken.origin.includes(arr[0]) && Date.now() / 1000 < parsedToken.exp) {
          const result = await http.post(api.appCookieInsert, {}, { headers: { token: token } });
          if (result) {
            setEnable(true);
          }
        }
      }
    }

    load();
  }, []);

  return enable ? <ScreenDetail /> : null;
}
