﻿using System;
using System.Threading;
using Esendex.Rest.App.builders;
using Esendex.Rest.App.factories;
using Esendex.Rest.App.services.interfaces;
using RestSharp;

namespace Esendex.Rest.App
{
    class Program
    {
        private static IClient _client;

        static void Main()
        {
            _client = ServiceFactory.CreateEsendexRestClient();

            var messageId = SendMessage();
            GetMessage(messageId);
            
            Console.ReadLine();
        }

        private static void GetMessage(Guid messageId)
        {
            var request = RequestBuilder.Create()
                                        .WithUri(string.Format("/v1.0/messageheaders/{0}", messageId))
                                        .WithMethod(Method.GET)
                                        .BuildGetRequest();

            var message = _client.GetMessage(request);
            while (!string.Equals(message.Status, "Delivered"))
            {
                Console.WriteLine("And wait..");
                message = _client.GetMessage(request);

                Thread.Sleep(2000);
            }

            Console.WriteLine("Champion! Your message was delivered!");
        }

        private static Guid SendMessage()
        {
            var messageBody = GetUserInputForMessageBody();
            string recipient = GetUserInputForRecipient();

            var sendRequest = RequestBuilder.Create()
                                            .WithRecipient(recipient)
                                            .WithMessageBody(messageBody)
                                            .WithUri("/v1.0/messagedispatcher")
                                            .WithMethod(Method.POST)
                                            .BuildSendRequest();

            var messageId = _client.SendMessage(sendRequest);
            Console.WriteLine("Sweet, your message was sent! Now we wait..");

            return messageId;
        }

        private static string GetUserInputForMessageBody()
        {
            Console.Write("Enter your message: ");
            var messageBody = Console.ReadLine();

            return messageBody;
        }

        private static string GetUserInputForRecipient()
        {
            Console.Write("Enter the phone number of your recipient: ");
            var recipient = Console.ReadLine();

            return recipient;
        }
    }
}
