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

using EQNetwork.Objects;
using EQNetwork.Services;
using EQNetwork.Interfaces;
using System.Reflection;
using System.IO;

namespace EQNetwork
{
    public class EQProcess : System.IDisposable
    {
        public Session Session { get { return SessionService.Session; } set { SessionService.Session = value; } }
        public Guid? SessionGuid { get { return Session == null ? null : Session.SessionGuid; } }
        public string AccessKey = "accesskey";
        public string Secret = "secret";

        public IEQApiService EQApiService;
        public ISessionService SessionService;
        public IUserService UserService;
        public ICollectionService CollectionService;
        public IContentFileService ContentFileService;
        public IPostService PostService;
        public IMiscService MiscService;
        public IUploadService UploadService;
        public IRequestService RequestService;

        public EQProcess(Guid sessionGuid, string accessKey, string secret)
        {
            Initialize(accessKey, secret);
            Session = new Session();
            Session.SessionGuid = sessionGuid;
        }

        public EQProcess(Session session, string accessKey, string secret)
        {
            Initialize(accessKey, secret);
            Session = session;
        }

        public EQProcess(string accessKey, string secret)
        {
            Initialize(accessKey, secret);
        }

        private void Initialize(string accessKey, string secret)
        {
            AccessKey = accessKey;
            Secret = secret;

            EQApiService = new EQApiService(this);
            SessionService = new SessionService(this);
            UserService = new UserService(this);
            CollectionService = new CollectionService(this);
            ContentFileService = new ContentFileService(this);
            PostService = new PostService(this);
            MiscService = new MiscService(this);
            UploadService = new UploadService(this);
            RequestService = new RequestService(this);
        }

        static byte[] StreamToBytes(Stream input)
        {
            var capacity = input.CanSeek ? (int)input.Length : 0;
            using (var output = new MemoryStream(capacity))
            {
                int readLength;
                var buffer = new byte[4096];

                do
                {
                    readLength = input.Read(buffer, 0, buffer.Length);
                    output.Write(buffer, 0, readLength);
                }
                while (readLength != 0);

                return output.ToArray();
            }
        }

        #region IDisposable Members

        public IDisposable IDisposable { get { return this; } }
        void IDisposable.Dispose()
        {
            if (EQApiService != null)
                EQApiService.IDisposable.Dispose();
        }

        #endregion
    }
}
