@using System.Net.Http;
@using System.Text.Json;
@using TSC2.Components.Layout;
@using TSC2.Components.CSharp;

@page "/signin-facebook"
<title>The Shop Critics</title>
@inject NavigationManager _navigationManager

@code {

    [Parameter][SupplyParameterFromQuery] public string? code { get; set; }
    [Parameter][SupplyParameterFromQuery] public string? scope { get; set; }
    [Parameter][SupplyParameterFromQuery] public string? authuser { get; set; }
    [Parameter][SupplyParameterFromQuery] public string? prompt { get; set; }

    protected override async Task OnAfterRenderAsync(bool firstRender) // Executes every page load; run inexpensive rendering code here
    {
        if (!firstRender)
            return;

        var dct = new Dictionary<string, string>();

        dct["client_id"] = TSC2.Components.CSharp.Credentials.FacebookAppId;
        dct["redirect_uri"] = TSC2.Components.Layout.MainLayout.FacebookRedirect;        
        dct["client_secret"] = TSC2.Components.CSharp.Credentials.FacebookClientSecret;    
        dct["code"] = code;

        try
        {
            string auth_json = "";
            string profile_json = "";

            // Get access token for the auth session
            using(var client = new HttpClient())
            using(var content = new FormUrlEncodedContent(dct))
            {
                HttpResponseMessage response = await client.GetAsync(string.Format("https://graph.facebook.com/v20.0/oauth/access_token?client_id={0}&redirect_uri={1}&client_secret={2}&code={3}", dct["client_id"], dct["redirect_uri"], dct["client_secret"], dct["code"]));
                auth_json = await response.Content.ReadAsStringAsync();
            }
            OAuthTokenResponse tokenResponse = JsonSerializer.Deserialize<OAuthTokenResponse>(auth_json);
            Console.WriteLine("AUTH: " + auth_json);
            // Use the access token to access their information; name, email, & token
            using (var client = new HttpClient())
            {
                var id_json = await client.GetStringAsync("https://graph.facebook.com/me?fields=id&access_token=" + tokenResponse.access_token);
                FacebookAuthResponse id_response = JsonSerializer.Deserialize<FacebookAuthResponse>(id_json);

                // Configure the request
                List<KeyValuePair<string, string>> requestData = new List<KeyValuePair<string, string>>();
                requestData.Add(new KeyValuePair<string, string>("access_token", tokenResponse.access_token));
                var request = new HttpRequestMessage
                {
                    Method = HttpMethod.Get,
                    RequestUri = new Uri("https://graph.facebook.com/me?access_token=" + tokenResponse.access_token),
                    Content = new FormUrlEncodedContent(requestData)
                };

                // Send the request
                var profile_task = await client.SendAsync(request);
                profile_json = await profile_task.Content.ReadAsStringAsync();
            }
            FacebookProfileResponse profileResponse = JsonSerializer.Deserialize<FacebookProfileResponse>(profile_json);


            Console.WriteLine("PROFILE: " + profile_json);

            if (MainLayout.Session.Count == 0) // Fpr security, only add to the session if nothing exists in the session.
            {
                // Add profile to session
                MainLayout.Session.Add("id", profileResponse.id);
                MainLayout.Session.Add("name", profileResponse.name);
                MainLayout.isSignedIn = true;
                MainLayout.UpdateGreeting();

                // Contact database
                DatabaseManager.SignInFacebook();
            }

            _navigationManager.NavigateTo("/");
        }
        catch (Exception ex)
        {
            // Handler
            Console.WriteLine("ERORR" + ex);
        }

    }



    // Data classes to handle the Http responses
    public class OAuthTokenResponse
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string refresh_token { get; set; }
        public string scope { get; set; }
        public string token_type { get; set; }
        public string id_token { get; set; }
        public string error { get; set; }
        public string error_description { get; set; }

        public bool IsSuccess => string.IsNullOrEmpty(error);
    }

    public class FacebookAuthResponse
    {
        public string id { get; set; }
    }

    public class FacebookProfileResponse
    {
        public string name { get; set; }
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string id { get; set; }
    }
}