package main

import (
	"log"
	"net"
	"os"
	"os/signal"
	"strings"
	"syscall"
)

func server(slideshowDir chan string) {

	defer os.Remove(sockfile)

	//Create a Unix domain socket and listen for incoming connections.
	socket, err := net.Listen("unix", sockfile)
	if err != nil {
		panic(err)
	}
	log.Println("listening on unix domain socket...")

	//cleanup sockfile
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		os.Remove(sockfile)
		os.Exit(1)
	}()

	for {
		//Accept incoming
		conn, err := socket.Accept()
		if err != nil {
			log.Fatal(err)
		}

		//handle connection in separate goroutine
		go func(conn net.Conn) {
			defer conn.Close()
			//create buffer for incoming data
			buf := make([]byte, 4096)

			//read data from connection
			n, err := conn.Read(buf)
			if err != nil {
				log.Fatal(err)
			}

			str := strings.TrimSpace(string(buf[:n]))
			slideshowDir <- str
			// newbg, err := pickRandomImage(str)
			// if err != nil {
			// 	panic(err)
			// }
			// hyprpaperSet(newbg)

		}(conn)
	}

}
