﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using arnvanhoutte.Core.Classes;
using arnvanhoutte.DataAccess.Interfaces;
using arnvanhoutte.Domain.Entities.Wunderlist;
using Newtonsoft.Json;
using Task = arnvanhoutte.Domain.Entities.Wunderlist.Task;

namespace arnvanhoutte.DataAccess.Repositories
{
    public class WunderlistRepository : IWunderlistRepository
    {
        private readonly HttpClient _client;
        private const string ClientId = "512868630e40a5492c76";
        private const string ClientSecret = "8f32f0bea036a5c6e6807b02865caa653ed9ea1896d5b43458edd8b462db";
        private const string ClientToken = "07b3662bc57dcc57c1ab83677daf39a8bbfbb2c17143dc44ff2c75916f2a";

        public WunderlistRepository(HttpClient client)
        {
            _client = client;
            _client.DefaultRequestHeaders.Add("X-Access-Token", ClientToken);
            _client.DefaultRequestHeaders.Add("X-Client-ID", ClientId);
        }

        private async Task<string> CreateRequestAsync(string url)
        {
            var response = await _client.GetAsync(url);
            if (!response.IsSuccessStatusCode) throw new Exception(response.ReasonPhrase);
            var ms = new MemoryStream();
            await response.Content.CopyToAsync(ms);
            lock (ms)
            {
                ms.Seek(0, SeekOrigin.Begin);

                var sr = new StreamReader(ms);
                var str = sr.ReadToEnd();
                return str;
            }
        }

        public async Task<dynamic> GetUserAsync()
        {
            return JsonConvert.DeserializeObject(await CreateRequestAsync("https://a.wunderlist.com/api/v1/user"));
        }

        public async Task<IEnumerable<List>> GetListsAsync()
        {
            return JsonConvert.DeserializeObject<IEnumerable<List>>(
                await CreateRequestAsync("https://a.wunderlist.com/api/v1/lists"));
        }

        public async Task<IEnumerable<Task>> GetTasksByListAsync(int id)
        {
            return JsonConvert.DeserializeObject<IEnumerable<Task>>(
                await CreateRequestAsync($"https://a.wunderlist.com/api/v1/tasks?list_id={id}"));
        }
    }
}