using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Pluto.Api;

namespace ChoiceMSLConnect
{
    /// <summary>
    /// MSL API for Choice
    /// </summary>
    public static class MSLApi
    {
        /// <summary>
        /// Is it a valid UserApiKey? Only if there is a Pin, it is valid.
        /// </summary>
        /// <param name="UserApiKey"></param>
        /// <returns>true if it is valid, false otherwise</returns>
        public static bool IsValidUserApiKey(string UserApiKey)
        {
            if (!String.IsNullOrEmpty(UserApiKey))
            {
                string Pin = RegistrationWrapper.RetrievePinForUserApiKey(UserApiKey);
                return !String.IsNullOrEmpty(Pin);
            }
            return false;
        }

        /// <summary>
        /// PostBilling to MSL Client
        /// </summary>
        /// <param name="UserApiKey"></param>
        /// <param name="billingPost"></param>
        /// <exception cref="Invalid BillingPost"></exception>
        /// <exception cref="Invalid ApiKey"></exception>
        /// <exception cref="Client Unreachable"></exception>
        public static bool PostBilling(string UserApiKey, bool bCheckClientConnectivityPriorCall, BillingPost1 billingPost)
        {   
            if(billingPost == null)
               throw new Exception("Invalid BillingPost");

            bool bIsValidUserKey = IsValidUserApiKey(UserApiKey);
            if(!bIsValidUserKey)
                throw new Exception("Invalid ApiKey");

            string ip;
            int port;

            if (RegistrationWrapper.GetApiMobile(UserApiKey, bCheckClientConnectivityPriorCall, out ip, out port))
            {
                Pluto.MSL.Api.API.SetNetworkSettings(ip, (uint)port);
                SystemAccessVerifier verifier = new SystemAccessVerifier(UserApiKey);
                bool bSuccess = Pluto.MSL.Api.API.PostBilling(verifier.SystemApiKey, billingPost);
                return bSuccess;
            }
            else
            {
                throw new Exception("Client Unreachable");
            }
        }



    }
}
