using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace EVCB_OCPP.WSServer.Service
{
    public class SMSService
    {
       async public Task<string> SendMessage(string phoneNumber, string message)
        {
            string errorMsg = string.Empty;
            int result = 0;
            try
            {
                errorMsg = string.Empty;
                HttpClient client = new HttpClient();
                StringBuilder url = new StringBuilder("http://smexpress.mitake.com.tw:7002/SpSendUtf?");
                url.Append("username=").Append(HttpUtility.UrlEncode("83196607SMS",
                    Encoding.UTF8));
                url.Append("&password=").Append(HttpUtility.UrlEncode("83196607SMS@nhoa.tcc",
                    Encoding.UTF8));
                url.Append("&encoding=UTF8");
                url.Append("&dstaddr=").Append(phoneNumber);
                url.Append("&smbody=").Append(HttpUtility.UrlEncode(message,
                    Encoding.UTF8).Replace("+", "%20"));
                url.Append("&CharsetURL=").Append("utf-8");

                var id = await client.GetStringAsync(url.ToString());

                if (!SendResult(id))
                {
                    result = -1;
                    errorMsg = id;
                }
            }
            catch (Exception ex)
            {
                result = -1;
                errorMsg = ex.Message;
            }

            return errorMsg;
        }

        private bool SendResult(string response)
        {
            bool result = false;

            if (response.Contains("msgid="))
            {
                result = true;

            }

            return result;
        }
    }
}
