Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
13 kB
2
Indexable
Never
import React, { useState, useEffect } from "react";
import { Card, CardContent, Box, Typography, NativeSelect, MenuItem, InputLabel, FormControl } from "@mui/material";
import styles from "../../../styles/Forms.module.css";
import dynamic from "next/dynamic";
const Chart = dynamic(() => import("react-apexcharts"), { ssr: false });
import axios from "api/axios";
import useSWR from "swr";
import Select1 from "@mui/material/Select";
import CustomWidthTooltip from "@/components/CustomToolTip";
import useMediaQuery from "@mui/material/useMediaQuery";
import { IconButton, TextField, Select } from "@mui/material";
import { AiOutlineInfoCircle } from "react-icons/ai";
import "@fontsource/poppins/600.css";

// const Modal = ({ isOpen, onClose, content }) => {
//   return isOpen ? (
//     <div style={{ position: "absolute", background: "#fff", boxShadow: "rgba(0, 0, 0, 0.24) 0px 3px 8px", zIndex: "10", marginLeft: "2%", width: "30%" }}>
//       <div>
//         <div style={{ display: "flex", margin: "5px" }}>
//           <span style={{ fontFamily: "Poppins", fontSize: "20px", paddingLeft: "10px", color: "#333" }} >Select Time duration</span>
//           {/* <h5>Select Time duration</h5> */}
//           <div style={{ marginLeft: "auto", cursor: "pointer", color:"red" }} onClick={onClose}>&times;</div>
//         </div>
//         <div className="modal-content">
//           {content}
//         </div>
//       </div>
//     </div>
//   ) : null;
// };

const APICalls = () => {

  const [apiData, setApiData] = useState("");




  const [period, setPeriod] = useState('');

  const handleChange = (event) => {
    setPeriod(event.target.value);
  };

  const isMobile = useMediaQuery("(max-width: 600px)");
  var countUnit = ""
  const tickAmount = 5

  const countUnitIndex = {
    "K": [3, 6],
    "M": [6, 9],
    "B": [9, 12],
  }

  const getCountUnit = (value) => {
    var strLen = String(value).length
    var unit = ""

    for (let key in countUnitIndex) {

      if (strLen > countUnitIndex[key][0] && strLen <= countUnitIndex[key][1]) {
        unit = key
        break
      }
    }

    return unit
  }

  const chartMaxCount = (max) => {
    countUnit = getCountUnit(max)

    var maxCount = 10 ** String(max).length
    var maxCopy = max

    if (countUnit !== "") {
      maxCount = maxCount / (10 ** countUnitIndex[countUnit][0])
      maxCopy = maxCopy / (10 ** countUnitIndex[countUnit][0])
    }

    for (let i = 0; i < 2; i++) {
      let halfCount = maxCount / 2
      if (halfCount > maxCopy) {
        maxCount = halfCount
      }
    }

    if (countUnit !== "") {
      maxCount = Math.ceil(maxCount / tickAmount) * (tickAmount) * (10 ** countUnitIndex[countUnit][0])
    } else {
      maxCount = Math.ceil(maxCount / tickAmount) * (tickAmount)
    }

    return maxCount
  }


  // const fetchInitialData = () => {
  //   // Step 4 (continued): Perform the initial API request
  //   // Replace 'apiEndpoint' with your API endpoint
  //   fetch(
  //     "http://localhost:5000" +
  //     `${process.env.NEXT_PUBLIC_GET_API_CALLS + "?duration=1&unit=month"}`,
  //     (url) =>
  //       axios.get(
  //         url,
  //         {
  //           headers: {
  //             Authorization: sessionStorage.getItem(
  //               `${process.env.NEXT_PUBLIC_SESSION_KEY}`
  //             ),
  //           },
  //         })
  //   )
  //     .then(response => {
  //       setApiData(response);
  //     })
  //     .catch(error => console.error('Error:', error));

  // };
  const [timeDurationOptions, settimeDurationOptions] = useState([
    {
      status: false,
      value: '1',
      duration: 'hour',
      displayval: '1h'
    },
    {
      status: false,
      value: '3',
      duration: 'hour',
      displayval: '3h'
    },
    {
      status: false,
      value: '12',
      duration: 'hour',
      displayval: '12h'
    },
    {
      status: true,
      value: '1',
      duration: 'day',
      displayval: '1d'
    },
    {
      status: false,
      value: '3',
      duration: 'day',
      displayval: '3d'
    },
    {
      status: false,
      value: '7',
      duration: 'day',
      displayval: '1w'
    },
    {
      status: false,
      value: '1',
      duration: 'month',
      displayval: '1m'
    },
    {
      status: false,
      value: '3',
      duration: 'month',
      displayval: '3m'
    },
    {
      status: false,
      value: '6',
      duration: 'month',
      displayval: '6m'
    },
    {
      status: false,
      value: '1',
      duration: 'year',
      displayval: '1y'
    },
  ]);

  const [options, setOptions] = useState({
    chart: {
      height: 350,
      zoom: {
        enabled: false,
      },
    },
    xaxis: {
      type: 'datetime',
      min: 0,//unixTimestamp - 5000, // Set the fixed minimum value
      max: 0,//unixTimestamp + 25000,
      labels: {
        show: true,
      }
    },
  });

  const [series, setSeries] = useState([
    {
      name: 'API Calls',
      data:
        [
          // Add more data points here.
        ],
    },
  ]);

  const [chartType, setChartType] = useState('line');

  const [lineActive, setlineActive] = useState(true);

  const toggleChartType = () => {
    setChartType(chartType === 'line' ? 'bar' : 'line');
    setlineActive(lineActive === true ? false : true);
  };

  const [duration, setDuration] = useState('');
  const [timeUnit, setTimeUnit] = useState('minutes');

  const handleDurationChange = (event) => {
    setDuration(event.target.value);
  };

  const handleTimeUnitChange = (event) => {
    setTimeUnit(event.target.value);
  };

  const handleSubmit = () => {
  };

  const [currentDurationId, setcurrentDurationId] = useState('1d');

  const [loading, setLoading] = useState(true);

  const changeTimeDuration = (index) => {

    setLoading(true);

    var updatedList = [...timeDurationOptions];
    updatedList.forEach((item, i) => {
      if (i !== index) {
        item['status'] = false;
      }
    });
    updatedList[index]['status'] = true;
    settimeDurationOptions(updatedList);

    var url = process.env.NEXT_PUBLIC_GET_API_CALLS + "?duration=" + updatedList[index]['value'] + "&unit=" + updatedList[index]['duration'];
    axios.get(url, {
      headers: {
        Authorization: sessionStorage.getItem(
          `${process.env.NEXT_PUBLIC_SESSION_KEY}`
        ),
      },
    })
      .then((response) => {
        response.data;
        setApiData(response.data);
        console.log("Updated API Data");

        var newoptions = options;
        newoptions['xaxis']['min'] = Date.parse(response.data.window_open_at);
        newoptions['xaxis']['max'] = Date.parse(response.data.window_close_at);
        setOptions(newoptions);

        const seriesData = [
          {
            name: 'API Calls',
            data: Array.isArray(response.data.data) ? response.data.data.map((item) => [
              Date.parse(item.time_window_open_at), // Convert the date string to a Date object
              item.count,
            ]) :
              [],
          },
        ]

        setSeries(seriesData);
        setLoading(false);
        setcurrentDurationId(updatedList[index]['displayval']);

        // console.log(options);
        // console.log(series);

      })
      .catch((err) => {
        throw err;
      });


    // console.log(apiData);

    // var newoptions = options;
    // newoptions['xaxis']['min'] = Date.parse(apiData.window_open_at);
    // newoptions['xaxis']['max'] = Date.parse(apiData.window_close_at);
    // setOptions(newoptions);
    // console.log("Options");
    // console.log(apiData.window_open_at)
    // console.log(apiData.window_close_at);

    // setcurrentDurationId(updatedList[index]['displayval']);
  };

  useSWR(
    `${process.env.NEXT_PUBLIC_GET_API_CALLS + "?duration=1&unit=day"}`,
    (url) =>
      axios.get(url, {
        headers: {
          Authorization: sessionStorage.getItem(
            `${process.env.NEXT_PUBLIC_SESSION_KEY}`
          ),
        },
      })
        .then((response) => {
          response.data;
          setApiData(response.data);
          console.log("Initial API Data");
          console.log(response.data);

          var newoptions = options;
          newoptions['xaxis']['min'] = Date.parse(response.data.window_open_at);
          newoptions['xaxis']['max'] = Date.parse(response.data.window_close_at);
          setOptions(newoptions);

          const seriesData = [
            {
              name: 'API Calls',
              data: Array.isArray(response.data.data) ? response.data.data.map((item) => [
                Date.parse(item.time_window_open_at), // Convert the date string to a Date object
                item.count,
              ]) :
                [],
            },
          ]

          setSeries(seriesData);
          setLoading(false);
          // setLoading(false);

        })
        .catch((err) => {
          throw err;
        })
  );

  return (
    <div style={{ background: "#fff", height: "26rem" }}>

      <Box p={2} display="flex" alignItems="center" backgroundColor={"#fff"} gap={"10px"} >
        <span style={{ fontFamily: "Poppins", fontSize: "20px", paddingLeft: "10px", color: "#333" }} >API calls</span>

        <CustomWidthTooltip
          title={"This chart provides a visual representation of the monthly volume of API calls, allowing you to easily track usage of APIs over time."}
          placement={isMobile ? "bottom" : "right-start"}
          arrow
        >
          <IconButton className="IconButton"><AiOutlineInfoCircle className="InfoCircle" /></IconButton>
        </CustomWidthTooltip>
        <div style={{ display: "flex", gap: "5px", padding: "2px", height: "35px", marginLeft: "auto" }}>
          {timeDurationOptions.map((timeOption, index) => (
            <div
              className={styles.TimeButton}
              style={{ color: timeOption.status ? "#26a0fc" : "#000" }}
              onClick={() => changeTimeDuration(index)}>
              {timeOption.displayval}
            </div>
          ))}
        </div>
        <div style={{ display: "flex", padding: "2px", height: "35px", cursor: "pointer" }} onClick={toggleChartType}>
          <div className={styles.toggleChartButton}
            style={{
              background: lineActive ? '#e4e4e4' : '#fff',
            }}
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 500 500" fill="none">
              <path d="M71.5 288L187 139L310.5 230L430.5 39" stroke="#26a0fc" stroke-width="23" stroke-linecap="round" stroke-linejoin="round" />
              <rect y="444" width="500" height="56" rx="15" fill="#26a0fc" />
              <circle cx="430" cy="40" r="40" fill="#26a0fc" />
              <circle cx="310" cy="230" r="40" fill="#26a0fc" />
              <circle cx="190" cy="140" r="40" fill="#26a0fc" />
              <circle cx="70" cy="285" r="40" fill="#26a0fc" />
            </svg>
          </div>
          <div className={styles.toggleChartButton}
            style={{
              background: lineActive ? '#fff' : '#e4e4e4',
            }}
          >
            <svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 500 500" fill="none">
              <path d="M25 260C25 251.716 31.7157 245 40 245H100C108.284 245 115 251.716 115 260V444H25V260Z" fill="#26a0fc" />
              <path d="M145 115C145 106.716 151.716 100 160 100H220C228.284 100 235 106.716 235 115V444H145V115Z" fill="#26a0fc" />
              <path d="M265 198C265 189.716 271.716 183 280 183H340C348.284 183 355 189.716 355 198V444H265V198Z" fill="#26a0fc" />
              <path d="M385 15C385 6.71573 391.716 0 400 0H460C468.284 0 475 6.71573 475 15V444H385V15Z" fill="#26a0fc" />
              <rect y="444" width="500" height="56" rx="15" fill="#26a0fc" />
            </svg>
          </div>
        </div>
      </Box>
      <div className={styles.chartsMain}>
        <div className={styles.charts}>
          {loading ? (
            // Display a loading indicator
            <div>Loading...</div>
          ) :
            (
              <Chart key={chartType + currentDurationId} options={options} series={series} type={chartType} height={"300px"} />
            )
          }
        </div>
      </div>

    </div>
  );
};

export default APICalls;