package server

import (
	"net/http"

	"github.com/gorilla/websocket"
)

func (s *Server) HandleClient(conn *websocket.Conn, r *http.Request) {
	clientSession := NewSession(conn)
	clientSession.Start()
	s.clientSession[clientSession.Id] = clientSession
	command := NcmdSession(clientSession.Id)
	clientSession.Send(command)
	clientSession.On("NewConnection", func(args ...interface{}) {
		orgPlayload := args[0].(map[string]string) // orgPayload should include target, host and port field
		targetSessionId, ok := orgPlayload["target"]

		if !ok {
			clientSession.Send(NewErrorResponse("target field is required", command))
			return
		}
		targetSession := s.findSession(targetSessionId)
		if targetSession == nil {
			clientSession.Send(NewErrorResponse("target session not found", command))
			return
		}
		spipe := NewPipe(clientSession.Id, targetSessionId)
		s.pipes[spipe.Id] = spipe
		command := NcmdConnectionInited(spipe.Id)

		for k, v := range orgPlayload {
			command.Payload[k] = v
		}
		clientSession.Send(command)
		targetSession.Send(command)

	})
}
