import ApiSecret from '../../private/portainer_api_secret.json'
import { DockerInfo } from '../../interfaces/DockerStatus';
import { ServiceLocation } from '../../interfaces/CardTypes';

export default async function ContainersAPI(req: any, res: any) {
  const token = JSON.parse(JSON.stringify(ApiSecret.token));

  try {
    const res1 = await fetch('https://portainer.neshweb.net/api/endpoints/2/docker/containers/json', {
      method: "GET",
      headers: {"X-API-Key": token}
    });

    const unparsed = await res1.json();
    let list: DockerInfo[] = [];

    unparsed.forEach((entry: any) => {
      let newEntry = {} as DockerInfo;

      newEntry.name = entry.Names[0].substring(1);
      newEntry.status = entry.State;
      newEntry.id = entry.Id;
      newEntry.location = ServiceLocation.tower_0;
      list.push(newEntry);
    });

    res.status(200).json(list);
  }
  catch (error) {
    console.log(error);
    res.status(500).json({ error: 'Error reading data' });
  }
}