using Microsoft.AspNetCore.Mvc;
using sodoff.Attributes;
using sodoff.Model;
using sodoff.Schema;
using sodoff.Services;
using sodoff.Util;

namespace sodoff.Controllers.Common;
public class MessagingController : Controller {

    private readonly MessagingService messagingService;
    private readonly DBContext ctx;
    public MessagingController(MessagingService messagingService, DBContext ctx)
    {
        this.messagingService = messagingService;
        this.ctx = ctx;
    }

    [HttpPost]
    [Produces("application/xml")]
    [Route("MessagingWebService.asmx/GetUserMessageQueue")]
    [VikingSession]
    public ArrayOfMessageInfo? GetUserMessageQueue(Viking viking, [FromForm] bool showOldMessages, [FromForm] bool showDeletedMessages) {
        return messagingService.ConstructUserMessageInfoArray(viking, showOldMessages, showDeletedMessages);
    }

    [HttpPost]
    [Produces("application/xml")]
    [Route("MessagingWebService.asmx/SendMessage")]
    [VikingSession]
    public IActionResult SendMessage(Viking viking, [FromForm] Guid toUser, [FromForm] int messageID, [FromForm] string data) {
        // find viking to send to
        Viking? toViking = ctx.Vikings.FirstOrDefault(e => e.Uid == toUser);
        if (toViking == null) return Ok(false);

        // clients (at least older ones) don't send what typeID the message is, its encoded in data
        ArrayOfKeyValuePairOfStringString arrayOfKeyValuePairOfStringString = XmlUtil.DeserializeXml<ArrayOfKeyValuePairOfStringString>(data);
        MessageTypeID typeID = MessageTypeID.Unknown;
        string typeText = "";

        switch(arrayOfKeyValuePairOfStringString.KeyValuePairOfStringString![0].Value)
        {
            case "Photo":
                typeID = MessageTypeID.Photo;
                typeText = "Photo";
                break;
            case "Drawing":
                typeID = MessageTypeID.GreetingCard;
                typeText = "Card";
                break;
        }

        var msg = messagingService.AddMessageToViking(viking, toViking, MessageType.Data, typeID, MessageLevel.WhiteList, data, "[[Line1]]=[[{{BuddyUserName}} has sent you a " + typeText + "!]]", "[[Line1]]=[[{{BuddyUserName}} has sent you a " + typeText + "!]]");
        if (msg != null) return Ok(true);
        else return Ok(false);
    }

    [HttpPost]
    [Produces("application/xml")]
    [Route("MessagingWebService.asmx/SaveMessage")]
    public IActionResult SaveMessage([FromForm] int userMessageQueueId, [FromForm] bool isNew, [FromForm] bool IsDeleted) {
        var updatedMessage = messagingService.UpdateMessageByQueueID(userMessageQueueId, isNew, IsDeleted);
        if (updatedMessage != null) return Ok(true);
        else return Ok(false);
    }

    [HttpPost]
    [Produces("application/xml")]
    [Route("MessageWebService.asmx/GetCombinedListMessage")]
    [VikingSession(UseLock = false)]
    public ArrayOfCombinedListMessage? GetCombinedListMessage(Viking viking, [FromForm] Guid userId)
    {
        // find viking
        Viking? uidViking = ctx.Vikings.FirstOrDefault(e => e.Uid == userId);

        if (viking != null && uidViking != null) return messagingService.ConstructCombinedMessageArray(viking, uidViking);
        else return new ArrayOfCombinedListMessage();
    }

    [HttpPost]
    [Produces("application/xml")]
    [Route("MessageWebService.asmx/RemoveMessageFromBoard")]
    public IActionResult RemoveMessageFromBoard([FromForm] int messageID)
    {
        messagingService.RemoveMessage(messageID);
        return Ok(true);
    }

    [HttpPost]
    [Route("Messaging/PostTextMessage")]
    public IActionResult PostTextMessage([FromForm] Guid token, [FromForm] Guid userId, [FromForm] string data, [FromForm] int messageLevel, [FromForm] int replyMessageId)
    {
        // check if session is valid
        Session? session = ctx.Sessions.FirstOrDefault(e => e.ApiToken == token);

        // find viking
        Viking? viking = ctx.Vikings.FirstOrDefault(e => e.Uid == userId);

        if (session != null && viking != null)
        {
            // post text message
            var message = messagingService.AddMessageToViking(session.Viking, viking, MessageType.Post, MessageTypeID.Messaging, (MessageLevel)messageLevel, data, isReply: replyMessageId > 0, parentMessageId: replyMessageId);

            if (message != null) return Ok(true);
        }

        return Ok(false);
    }
}
