package main

import (
	"errors"
	"flag"
	"fmt"
	"log"
	"net/http"
	"strconv"
	//wss "git.alfi.li/gamelang/frontend/wsserver"
)

type ExampleConfig struct {
	Http struct {
		Listen string // ip:port
	}
	Kafka struct {
		Enabled            bool
		UserManagerBroker  string
		WorldManagerBroker string
	}
}

func DefaultConfig() ExampleConfig {
	config := ExampleConfig{}
	config.Http.Listen = "0.0.0.0:8080"
	config.Kafka.Enabled = false
	return config
}

type WebRTCPeer struct {
	id int
	ws *WSPeer
}

type exampleWSServer struct {
	wsserver WSServer
	peers    map[int]*WebRTCPeer
}

func (ewss exampleWSServer) register(peer *WSPeer) *WebRTCPeer {
	id := 1
	if len(ewss.peers) > 0 {
		for i := 2; i <= len(ewss.peers); i++ {
			_, ok := ewss.peers[i]
			if !ok {
				id = i
				break
			}
		}
		if id == 1 {
			id = len(ewss.peers) + 1
		}
	}

	wrtcPeer, ok := ewss.peers[id]
	if ok {
		wrtcPeer.ws = peer
	} else {
		wrtcPeer = &WebRTCPeer{id: id, ws: peer}
		ewss.peers[id] = wrtcPeer
	}
	msg := WSMsg{ID: id, Mtype: "I", Payload: strconv.Itoa(id)}
	peer.Answer(msg)
	return wrtcPeer
}

func (ewss exampleWSServer) unregister(peer WebRTCPeer) {
	delete(ewss.peers, peer.id)
}

func (ewss exampleWSServer) getWebRTCPeerFromWSPeer(wspeer *WSPeer) *WebRTCPeer {
	for _, webRTCPeer := range ewss.peers {
		if wspeer.uuid == webRTCPeer.ws.uuid {
			return webRTCPeer
		}
	}
	return nil
}

func (ewss exampleWSServer) RenderHandler() []Handler {
	handler := []Handler{}
	handler = append(handler, Handler{MType: "echo", Callback: func(msg WSMsg, peer *WSPeer) error {
		log.Printf("echo from \"%s\" with \"%s\"", peer.uuid.String(), msg.Payload)
		remsg := WSMsg{Mtype: "echo", Payload: msg.Payload}
		peer.Answer(remsg)
		return nil
	}})
	handler = append(handler, Handler{MType: "J", Callback: func(msg WSMsg, peer *WSPeer) error {
		peer.Answer(WSMsg{Mtype: "J", Payload: "default"})
		log.Printf("join from \"%s\" with \"%s\"", peer.uuid.String(), msg.Payload)
		webRTCPeer := ewss.register(peer)
		for otherPeerID, _ := range ewss.peers {
			//if otherPeerID == webRTCPeer.id {
			//	continue
			//}
			peerMsg := WSMsg{Mtype: "N", Payload: strconv.Itoa(webRTCPeer.id)}
			go ewss.peers[otherPeerID].ws.Answer(peerMsg)
		}
		return nil
	}})

	handler = append(handler, Handler{MType: "O", Callback: func(msg WSMsg, peer *WSPeer) error {
		log.Printf("offer from \"%s\" for \"%d\"", peer.uuid.String(), msg.ID)
		otherPeer, ok := ewss.peers[msg.ID]
		if !ok {
			return errors.New(fmt.Sprintf("Peer with id \"%d\" not found", msg.ID))
		}
		otherPeer.ws.Answer(WSMsg{Mtype: "O", Payload: msg.Payload, ID: msg.ID})
		return nil
	}})

	handler = append(handler, Handler{MType: "A", Callback: func(msg WSMsg, peer *WSPeer) error {
		log.Printf("answer from \"%s\" with \"%s\"", peer.uuid.String(), msg.Payload)
		otherPeer := ewss.peers[msg.ID]
		otherPeer.ws.Answer(WSMsg{Mtype: "A", Payload: msg.Payload, ID: msg.ID})
		return nil
	}})

	handler = append(handler, Handler{MType: "C", Callback: func(msg WSMsg, peer *WSPeer) error {
		log.Printf("candidate from \"%s\" with \"%s\"", peer.uuid.String(), msg.Payload)
		otherPeer := ewss.peers[msg.ID]
		otherPeer.ws.Answer(WSMsg{Mtype: "C", Payload: msg.Payload, ID: msg.ID})
		return nil
	}})

	return handler
}

func main() {
	wsPtr := flag.String("ws", ":8080", "websocket listen port")
	wssPtr := flag.String("wss", ":8443", "wesocker secure listen port")
	certPtr := flag.String("cert", "", "wesocker secure server certificate")
	keyPtr := flag.String("key", "", "wesocker secure server key")
	flag.Parse()
	wsserver := NewWSServer()

	ewss := exampleWSServer{wsserver: *wsserver}
	ewss.peers = map[int]*WebRTCPeer{}
	ewss.wsserver.RegisterHandler(ewss.RenderHandler())

	http.HandleFunc("/play", ewss.wsserver.WebsocketHandler)
	log.Println("websocket listening on", *wsPtr)
	go http.ListenAndServe(*wsPtr, nil)
	log.Println("websocket listening on", *wssPtr)
	err := http.ListenAndServeTLS(*wssPtr, *certPtr, *keyPtr, nil)
	if err != nil {
		fmt.Println(err.Error())
	}
}
