package cn.sagacloud.server

/*
 * Author: Jxing
 * Create Time: 2019/3/20
 */

import cn.sagacloud.proto.MessageProtoStr
import cn.sagacloud.proto.MessageUtil
import cn.sagacloud.server.scheduler.pojo.ChannelHandlerContextWrapper
import cn.sagacloud.server.scheduler.pojo.*
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInboundHandlerAdapter

import java.net.SocketAddress
import java.util.ArrayList
import java.util.HashMap
import java.util.concurrent.ConcurrentHashMap

class SchedulerHandler(internal var clientList: ArrayList<ChannelHandlerContextWrapper>) : ChannelInboundHandlerAdapter() {
    private var ctxw: ChannelHandlerContextWrapper? = null

    /**
     * 刚添加上handler的时候    1
     * @param ctx
     */
    override fun handlerAdded(ctx: ChannelHandlerContext?) {
        //SocketAddress addr = ctx.channel().remoteAddress();
        println("client incoming")
    }

    /**
     * 客户端活动状态         2
     * @param ctx
     */
    override fun channelActive(ctx: ChannelHandlerContext) {
        ctxw = ChannelHandlerContextWrapper(ctx)
        this.clientList.add(ctxw!!)
        ctx.channel().writeAndFlush(MessageUtil.buildMessage(Command.ClientInfo.name, "", ""))
    }

    /**
     * 客户端服务器互发消息      3
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Throws(Exception::class)
    override fun channelRead(ctx: ChannelHandlerContext, msg: Any) {
        try {
            // Do something with msg
            val message = msg as MessageProtoStr.Message
            MessageHandler.offer(ClientMessage(ctxw, message))
            ctx.channel().writeAndFlush(MessageUtil.buildMessage(Command.HeartBeat.name, "", ""))
        } catch (e : Exception){
            println("Read Exception : ${e.message}")
        }finally {
            // 如果ctx write 或 writeAndFlush过的话, 就不用释放msg
            //ReferenceCountUtil.release(msg);
        }
    }

    /**
     * 客户端异常原因  4
     * @param ctx
     * @param cause
     */
    override fun exceptionCaught(ctx: ChannelHandlerContext, cause: Throwable) {
        println("client exceptionCaught : " + cause.message)
    }

    /**
     * 客户端非活动状态  5
     * @param ctx
     */
    override fun channelInactive(ctx: ChannelHandlerContext) {
        println("client channelInactive")
    }

    /**
     * 客户端断开连接 6
     * @param ctx
     */
    override fun handlerRemoved(ctx: ChannelHandlerContext?) {
        this.clientList.remove(ctxw)
        try {
            for (i in ctxw!!.taskSendingStatusMap){
                if(DispatchTask.tasks!!.containsKey(i.key))
                    DispatchTask.tasks!![i.key]!!.status = 0;
            }
        }catch (e : Exception){}
    }

    companion object {
        // Map<当前状态, Map<可接受的命令, 接受完命令后的状态>>
        var statusTransitionMap: MutableMap<TaskStatus, Map<Command, TaskStatus>> = ConcurrentHashMap()

        init {
            val waitingMap = HashMap<Command, TaskStatus>()
            val sendingMap = HashMap<Command, TaskStatus>()
            val sentMap = HashMap<Command, TaskStatus>()
            val fileDownloadExceptionMap = HashMap<Command, TaskStatus>()
            val commandExceptionMap = HashMap<Command, TaskStatus>()
            statusTransitionMap[TaskStatus.Waiting] = waitingMap//CommonUtil.createSet(Command.TaskSuccess));
            statusTransitionMap[TaskStatus.Sending] = sendingMap//CommonUtil.createSet(Command.AcceptTask, Command.RefuseTask, Command.TaskSuccess));
            statusTransitionMap[TaskStatus.Sent] = sentMap//CommonUtil.createSet(Command.CommandError, Command.DownloadError, Command.TaskSuccess));
            statusTransitionMap[TaskStatus.FileDownloadException] = fileDownloadExceptionMap//CommonUtil.createSet(Command.TaskSuccess));
            statusTransitionMap[TaskStatus.CommandExecuteException] = commandExceptionMap//CommonUtil.createSet(Command.TaskSuccess));
            statusTransitionMap[TaskStatus.Finished] = HashMap()

            waitingMap[Command.TaskSuccess] = TaskStatus.Finished
            waitingMap[Command.DownloadError] = TaskStatus.FileDownloadException
            waitingMap[Command.CommandError] = TaskStatus.CommandExecuteException
            waitingMap[Command.AcceptTask] = TaskStatus.Sent

            sendingMap[Command.AcceptTask] = TaskStatus.Sent
            sendingMap[Command.RefuseTask] = TaskStatus.Waiting
            sendingMap[Command.TaskSuccess] = TaskStatus.Finished
            sendingMap[Command.DownloadError] = TaskStatus.FileDownloadException
            sendingMap[Command.CommandError] = TaskStatus.CommandExecuteException

            sentMap[Command.TaskSuccess] = TaskStatus.Finished
            sentMap[Command.DownloadError] = TaskStatus.FileDownloadException
            sentMap[Command.CommandError] = TaskStatus.CommandExecuteException

            fileDownloadExceptionMap[Command.TaskSuccess] = TaskStatus.Finished
            commandExceptionMap[Command.TaskSuccess] = TaskStatus.Finished
        }
    }
}
