package backend

import (
	"context"
	"get-container/docker"
	"strconv"
	"strings"
	"sync"

	"github.com/moby/moby/client"
)

type ContainerInfo struct {
	Name string
	Id   string
}

type DockerProcessMap struct {
	lock sync.RWMutex
	pids map[int32]*ContainerInfo
}

func (m *DockerProcessMap) Update() error {
	cli, err := docker.GetDockerClient()
	if err != nil {
		return err
	}
	defer cli.Close()
	cs, err := cli.ContainerList(context.Background(), client.ContainerListOptions{All: false})
	if err != nil {
		return err
	}
	if m.pids == nil {
		m.pids = make(map[int32]*ContainerInfo)
	}
	m.lock.Lock()
	defer m.lock.Unlock()
	clear(m.pids)
	for _, v := range cs {
		top, err := cli.ContainerTop(context.Background(), v.ID, []string{"-o", "pid"})
		if err != nil {
			continue
		}
		cinfo := &ContainerInfo{Name: strings.Trim(v.Names[0], "/"), Id: v.ID}
		for _, pid := range top.Processes {
			if len(pid) == 0 {
				continue
			}
			p, err := strconv.ParseInt(pid[0], 10, 32)
			if err != nil {
				continue
			}
			m.pids[int32(p)] = cinfo
		}
	}
	return nil
}

func (m *DockerProcessMap) Get() (map[int32]*ContainerInfo, sync.Locker) {
	rl := m.lock.RLocker()
	rl.Lock()
	return m.pids, rl
}
