using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Telepathy;
using PhilExample.Interfaces;
using PhilExampleCrawler.Common.Models;
using PhilExampleCrawler.Common.TCP.Enums;
using PhilExampleCrawler.Common.TCP.Packets;
using PhilExampleCrawler.Common.TCP.Utils;
using Xamarin.Forms;

namespace PhilExample.Services
{

    internal interface ICrawlService_CH
    {
        Task<User> LoginAsync(string authCode);
        Task<bool> LogoutAsync();
        Task<List<CrawlSession>> GetCrawlSessionsAsync(int userID);
        Task<CrawlSession> RegisterCrawlSessionAsync(int userID, CrawlSearchParams csp);
        Task<bool> DeleteCrawlSessionAsync(int crawlSessionID);
    }

    public class CrawlService_CH : ICrawlService_CH
    {
        readonly IRESTAccess _rest = DependencyService.Get<IRESTAccess>();
        static readonly string _url_user = App.WebAPI_URL + "User";
        static readonly string _url_crawlSession = App.WebAPI_URL + "CrawlSession";

        /// <summary> Returns null if no user found </summary>
        public async Task<User> LoginAsync(string authCode)
        {
            string url = _url_user + $"?authCode={authCode}";
            var user = await _rest.GetAsync<User>(url);
            return user;
        }

        public Task<bool> LogoutAsync()
        {
            throw new NotImplementedException();
        }

        /// <summary> Returns null if no user found </summary>
        public async Task<User> CreateUserAsync(string authCode)
        {
            string url = _url_user + $"?authCode={authCode}";
            var user = await _rest.PostAsync<User>(url);
            return user;
        }

        public async Task<List<CrawlSession>> GetCrawlSessionsAsync(int userID)
        {
            string url = _url_crawlSession + $"?userID={userID}";
            var sess = await _rest.GetAsync<List<CrawlSession>>(url);
            return sess;
        }

        public async Task<CrawlSession> RegisterCrawlSessionAsync(int userID, CrawlSearchParams csp)
        {
            string url = _url_crawlSession + $"?userID={userID}";
            var sess = await _rest.PostAsync<CrawlSession>(url, csp);
            return sess;
        }

        public async Task<bool> DeleteCrawlSessionAsync(int crawlSessionID)
        {
            string url = _url_crawlSession + $"?crawlSessionID={crawlSessionID}";
            bool deleted = await _rest.DeleteAsync(url);
            return deleted;
        }


        public void OnStop()
        {
            //TODO: when this happens, reconnect or stuff
            throw new NotImplementedException();
        }
    }
}

