using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using static BaroSeeSDK.AuthenticationProvider;
using static BaroSeeSDK.BaroSeeService;

namespace BaroSeeSDK.Example
{
    public class BaroSeeWorker
    {
        public BaroSeeService SDK { get; internal set; }
        private string publicKey, privateKey, accessToken;        

        public BaroSeeWorker()
        {            
        }

        public void Configure(string publicKey, string privateKey, string accessToken = null)
        {
            this.publicKey = publicKey;
            this.privateKey = privateKey;
            this.accessToken = accessToken;

            if (string.IsNullOrEmpty(accessToken))
                SDK = new BaroSeeService(publicKey, privateKey, BaroSeeGlobalErrorHandler);
            else
                SDK = new BaroSeeService(new AccessToken() { Value = accessToken },
                    //Create a local error handler to detect if access token is expired or invalid
                    delegate (string senderId, HttpStatusCode code, string message)
                    {
                        if (code == HttpStatusCode.Unauthorized)
                        {   //Try to use public/private key to get new access token
                            SDK = new BaroSeeService(publicKey, privateKey, BaroSeeGlobalErrorHandler);
                        }

                        //Call default global error hander
                        BaroSeeGlobalErrorHandler(senderId, code, message);
                    }
            );
            SDK.AuthenticationProvider.OnAccessTokenChanged += new AccessTokenChangedEvent(delegate (AccessToken token)
            {
                if (this.OnAccessTokenChanged != null) this.OnAccessTokenChanged.Invoke(token);
            });
            if (this.accessToken != this.SDK.AuthenticationProvider.CurrentAccessToken.Value)
            {
                if (this.OnAccessTokenChanged != null) this.OnAccessTokenChanged.Invoke(SDK.AuthenticationProvider.CurrentAccessToken);
            }
        }

        protected static void BaroSeeGlobalErrorHandler(string sender, HttpStatusCode code, string message)
        {
            switch (code)
            {
                case HttpStatusCode.Unauthorized:
                    //Write log or notify administrator
                    break;
                default:
                    break;
            }
        }

        #region Events
        public event AccessTokenChangedEvent OnAccessTokenChanged;
        #endregion
    }
}