namespace TeamViewerApi.TeamViewer
{
    using System;
    using System.Net;
    using System.Runtime.Serialization;
    using Newtonsoft.Json;

    [DataContract]
    public class Contacts
    {
        [DataMember(Name = "contacts")]
        public Contact[] Items { get; set; }

        /// <summary>
        /// Get contacts for the account
        /// </summary>
        /// <param name="accessToken">Token</param>
        /// <param name="email">Select with email contains ...</param>
        /// <param name="onlineOnly">Select only with state == Online</param>
        /// <param name="groupId">Select only with groupid == ...</param>
        /// <param name="includeInvitations">Include pending invitations</param>
        public static Contacts GetContacts(string accessToken, string email = "", bool onlineOnly = false, string groupId = "", bool includeInvitations = false)
        {
            string url = TeamViewer.URL.CONTACTS;

            if (!string.IsNullOrEmpty(email))
                url += "?email=" + email;

            if (onlineOnly)
            {
                if (!string.IsNullOrEmpty(email))
                    url += "&online_state=true";
                else
                    url += "?online_state=true";
            }

            if (!string.IsNullOrEmpty(groupId))
            {
                if (!string.IsNullOrEmpty(email) || onlineOnly)
                    url += "&groupid=" + groupId;
                else
                    url += "?groupid=" + groupId;
            }

            if(includeInvitations)
            {
                if (!string.IsNullOrEmpty(email) || onlineOnly || !string.IsNullOrEmpty(groupId))
                    url += "&include_invitations=true";
                else
                    url += "?include_invitations=true";
            }

            Rest.Properties properties = new Rest.Properties(accessToken, url, Rest.Method.GET);
            Rest.Connection connection = new Rest.Connection(properties);

            string json = connection.SendRequest();

            Contacts result = null;

            if (!string.IsNullOrEmpty(json))
                result = JsonConvert.DeserializeObject<Contacts>(json);

            return result;
        }
    }
}
