using C1.Web.Api.Storage;
using System;
using System.Collections.Specialized;

namespace WebApi
{
    internal class OneDriveStorageProvider : IStorageProvider
    {
        private string _accessToken;
        private DateTime _expiry;

        internal string ClientId { get; set; }
        internal string Scope { get; set; }
        internal string UserName { get; set; }
        internal string Password { get; set; }

        public OneDriveStorageProvider(string clientId, string scope, string username, string password)
            : base()
        {
            ClientId = clientId;
            Scope = scope;
            UserName = username;
            Password = password;
        }

        private string getAccessToken()
        {
            if (string.IsNullOrEmpty(_accessToken) || _expiry < DateTime.Now)
            {
                _accessToken = OAuth.AccessTokenGenerator.GetAccessToken(ClientId, Scope, UserName, Password, 30000);
                _expiry = DateTime.Now.AddMinutes(50);
            }
            return _accessToken;
        }

        public IFileStorage GetFileStorage(string name, NameValueCollection args = null)
        {
            name = name ?? string.Empty;
            var filepath = name.Replace("\\", "/").TrimStart('/');
            var accessToken = getAccessToken();
            var fileurl = "https://api.onedrive.com/v1.0/drive/root:/" + filepath + ":/content?access_token=" + accessToken;
            return new HTTPStorage(name, fileurl);
        }

        public IDirectoryStorage GetDirectoryStorage(string name, NameValueCollection args = null)
        {
            throw new NotImplementedException();
        }
    }
}
