import React, { useState, useEffect } from "react";
import { useParams } from "react-router";

import { useManifestsContext } from "../../Contexts/ManifestsContext";
import { useStatusContext } from "../../Contexts/StatusContext";
import { useUserContext } from "../../Contexts/UserContext";
import useStyles from "../../useStyles";

const getMemoryRegion = (label, region) => {
  if (!region) return "";
  return `, ${label}: [Offset: ${region.offset}, Length: ${region.length}]`;
};

const getFilename = (url) => {
  const items = url.split("/");
  return items[items.length - 1];
};

const ECUFileList = (files) => {
  if (!files || files.length === 0) return "No files";
  return (
    <ul>
      {files.map((file) => (
        <li key={file.file_id}>
          <a href={file.url}>{getFilename(file.url)}</a>
          {`, File ID: ${file.file_id}, Type: ${file.type}, Download Size: ${file.file_size
            }, CRC32: ${file.checksum ?? "00000000"}
          ${getMemoryRegion("Write", file.write_region)}
          ${getMemoryRegion("Erase", file.erase_region)}`}
        </li>
      ))}
    </ul>
  );
};

const ECUList = (ecus) => {
  const none = "None";
  if (!ecus || ecus.length === 0) return none;

  return (
    <ul>
      {ecus.map((ecu) => {
        const name = ecu.name;
        const version = ecu.version ?? none;
        const hardwareVersions = ecu.hw_versions?.join(", ") ?? ecu.hw_version ?? none;
        let mode = ecu.mode ?? "D";
        if (ecu.self_download) {
          mode += ", Self Download"
        }

        return (
          <li key={ecu.name}>
            {`${name}, SW Version: ${version}, HW Version: ${hardwareVersions}, Mode: ${mode}`}
            <br />
            {ECUFileList(ecu.files)}
          </li>
        )
      })}
    </ul>
  );
};

const ManifestDetails = ({ opened }) => {
  const classes = useStyles();
  const { manifest_id } = useParams();
  const [manifest, setManifest] = useState(null);
  const [open, setOpen] = useState(opened || false);
  const { getManifest } = useManifestsContext();
  const { setMessage } = useStatusContext();
  const {
    token: {
      idToken: { jwtToken: token },
    },
  } = useUserContext();

  const init = async () => {
    try {
      const result = await getManifest(manifest_id, token);
      if (result.error) {
        throw new Error(`Get manifest error. ${result.message}`);
      } else {
        setManifest(result);
      }
    } catch (e) {
      setMessage(e.message);
    }
  };

  const toggleOpen = (e) => {
    e.preventDefault();
    setOpen(!open);
  };

  useEffect(() => {
    if (!open || manifest) return;
    init();
    // eslint-disable-next-line
  }, [open]);

  if (!open)
    return (
      <div className={classes.link} onClick={(e) => toggleOpen(e)}>
        Show Details
      </div>
    );
  if (manifest === null) return <div>Loading Manifest...</div>;

  return (
    <>
      <div className={classes.link} onClick={(e) => toggleOpen(e)}>
        Hide Details
      </div>
      <ul>
        <li>{`${manifest.name} ${manifest.version} [${manifest.type || "standard"
          }]`}</li>
        <li>{`${manifest.description} ${manifest.release_notes}`}</li>
        <li>ECUs: {ECUList(manifest.ecu_updates)}</li>
      </ul>
    </>
  );
};

export default ManifestDetails;
