﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using arnvanhoutte.DataAccess.Interfaces;
using arnvanhoutte.Domain.Entities.Polar;
using Newtonsoft.Json;

namespace arnvanhoutte.DataAccess.Repositories
{
    public class HotmailRepository : IHotmailRepository
    {
        private readonly string _clientCode;
        private readonly string _clientId;
        private readonly string _clientSecret;
        private static string _clientToken;

        public HotmailRepository()
        {
            _clientCode = "M0490874b-92b3-0afc-523c-bbadf9c6d210";
            _clientToken = "753be98b856576abc630fdf0a2849510";
#if DEBUG
            _clientId = "000000004820D621";
        _clientSecret = "opcHTG5lcxiGKKI0233;(_]";
#else   
        _clientId = "f7d04b68-03d9-4179-9f05-fa0840ea5db9";
        _clientSecret = "fcd6d657-51f0-45a7-9a6c-f73b8e890b7e";
#endif
        }

        private async Task GetToken()
        {
            using (var client = new HttpClient())
            {
                var content = new FormUrlEncodedContent(new[]
                {
                    new KeyValuePair<string, string>("grant_type", "authorization_code"),
                    new KeyValuePair<string, string>("code", _clientCode),
                    new KeyValuePair<string, string>("redirect_uri", "https://localhost:5555/api/hotmail/oauth"),
                    new KeyValuePair<string, string>("client_id", _clientId),
                    new KeyValuePair<string, string>("client_secret", _clientSecret)
                });

                var response = await client.PostAsync("https://login.microsoftonline.com/common/oauth2/v2.0/token",
                    content);
                if (!response.IsSuccessStatusCode)
                {
                    throw new Exception(response.ReasonPhrase);
                }

                var obj = JsonConvert.DeserializeObject<Token>(await response.Content.ReadAsStringAsync());
                _clientToken = obj.AccessToken;
            }
        }

        public async Task<object> GetCalendarAsync()
        {
            await GetToken();
            return null;
        }
    }
}