summaryrefslogtreecommitdiff
path: root/modules/mono/editor/GodotTools/GodotTools.IdeMessaging.CLI/ForwarderMessageHandler.cs
blob: 3cb6a6687e6e6be9aca384d8e49792d1d19be2b4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using GodotTools.IdeMessaging.Utils;

namespace GodotTools.IdeMessaging.CLI
{
    public class ForwarderMessageHandler : IMessageHandler
    {
        private readonly StreamWriter outputWriter;
        private readonly SemaphoreSlim outputWriteSem = new SemaphoreSlim(1);

        public ForwarderMessageHandler(StreamWriter outputWriter)
        {
            this.outputWriter = outputWriter;
        }

        public async Task<MessageContent> HandleRequest(Peer peer, string id, MessageContent content, ILogger logger)
        {
            await WriteRequestToOutput(id, content);
            return new MessageContent(MessageStatus.RequestNotSupported, "null");
        }

        private async Task WriteRequestToOutput(string id, MessageContent content)
        {
            using (await outputWriteSem.UseAsync())
            {
                await outputWriter.WriteLineAsync("======= Request =======");
                await outputWriter.WriteLineAsync(id);
                await outputWriter.WriteLineAsync(content.Body.Count(c => c == '\n').ToString());
                await outputWriter.WriteLineAsync(content.Body);
                await outputWriter.WriteLineAsync("=======================");
                await outputWriter.FlushAsync();
            }
        }

        public async Task WriteResponseToOutput(string id, MessageContent content)
        {
            using (await outputWriteSem.UseAsync())
            {
                await outputWriter.WriteLineAsync("======= Response =======");
                await outputWriter.WriteLineAsync(id);
                await outputWriter.WriteLineAsync(content.Body.Count(c => c == '\n').ToString());
                await outputWriter.WriteLineAsync(content.Body);
                await outputWriter.WriteLineAsync("========================");
                await outputWriter.FlushAsync();
            }
        }

        public async Task WriteLineToOutput(string eventName)
        {
            using (await outputWriteSem.UseAsync())
                await outputWriter.WriteLineAsync($"======= {eventName} =======");
        }
    }
}