package transcoder

import (
	"context"

	pb "git.autistici.org/ale/autoradio/proto"
	"github.com/golang/protobuf/proto"
	"go.etcd.io/etcd/clientv3/concurrency"
)

var electionPath = "/icecast/5/election/transcoder/"

type Manager struct {
	nodeID      string
	ctx         context.Context
	session     *concurrency.Session
	transcoders map[string]*transcoder
}

func (t *Manager) Reset(mounts map[string]*pb.Mount) {
	// Figure out what the differences are.
	newTC := make(map[string]*transcoder)
	for path, m := range mounts {
		if !m.HasTranscoder() {
			continue
		}
		tc, ok := t.transcoders[path]
		if !ok || !proto.Equal(tc.mount, m) {
			tc = newTranscoder(t.ctx, t.session, m, t.nodeID)
		}
		delete(t.transcoders, path)
		newTC[path] = tc
	}
	for _, tc := range t.transcoders {
		tc.stop()
	}

	t.transcoders = newTC
}

func (t *Manager) Set(m *pb.Mount) {
	tc, ok := t.transcoders[m.Path]
	if ok && proto.Equal(tc.mount, m) {
		return
	}
	if ok {
		tc.stop()
	}
	tc = newTranscoder(t.ctx, t.session, m, t.nodeID)
	t.transcoders[m.Path] = tc
}

func (t *Manager) Delete(path string) {
	tc, ok := t.transcoders[path]
	if ok {
		tc.stop()
		delete(t.transcoders, path)
	}
}