package cn.sagacloud.server


import cn.sagacloud.proto.MessageProtoStr
import cn.sagacloud.proto.MessageUtil
import cn.sagacloud.server.scheduler.pojo.ChannelHandlerContextWrapper
import cn.sagacloud.server.scheduler.pojo.ClientMessage
import cn.sagacloud.server.scheduler.pojo.Command

import java.util.concurrent.ConcurrentLinkedQueue

class MessageHandler : Runnable {

    override fun run() {
        while (true) {
            val clientMessage = messageQueue.poll()
            if (clientMessage == null) {
                try {
                    Thread.sleep(500)
                } catch (e: InterruptedException) {
                    e.printStackTrace()
                }

                continue
            }
            handle(clientMessage.message, clientMessage.ctxWrapper)
        }
    }

    companion object {
        var messageQueue = ConcurrentLinkedQueue<ClientMessage>()

        fun handle(message: MessageProtoStr.Message?, clientWrapper: ChannelHandlerContextWrapper?) {
            val cmd: Command
            try {
                cmd = Command.valueOf(message!!.cmd)
            } catch (ex: Exception) {
                return
            }

            when (cmd) {
                Command.AcceptTask -> clientWrapper!!.acceptTask(message.taskId)
                Command.RefuseTask -> clientWrapper!!.setLastRejectTime(message.taskId)
                Command.ClientInfo -> clientWrapper!!.clientInfo = message.content
                Command.TaskSuccess -> clientWrapper!!.taskSuccess(message)
                Command.CommandError -> clientWrapper!!.commandError(message)
                Command.DownloadError -> clientWrapper!!.downloadError(message)
            }
        }

        fun offer(clientMessage: ClientMessage) {
            MessageUtil.printMessage(clientMessage.message!!)
            messageQueue.offer(clientMessage)
        }
    }
}




