using System;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;

namespace StateJobsNYSubmit.Pages
{
    public class IndexModel : PageModel
    {
        private readonly ILogger<IndexModel> _logger;
        private PrivateData p = new PrivateData();
        public UserData userData;
        public string Posting_ID { get; set; }
        public string CoverLetter { get; set; }
        public Posting posting = null;
        public IndexModel(ILogger<IndexModel> logger)
        {
            _logger = logger;
        }


        public void GetUserData()
        {
            userData = new UserData();
            userData.skillOptions = new List<string>();
            userData.visitCounter = 1;
            string cookieValue = Request.Cookies["PrivateData"];
            if (cookieValue != null)
            {
                string test = p.DecryptString(cookieValue);
                userData = JsonConvert.DeserializeObject<UserData>(test);
                userData.visitCounter++;

                Response.Cookies.Append("PrivateData", p.EncryptString(JsonConvert.SerializeObject(userData)));

                userData.coverLetter = Request.Cookies["CoverLetter"];
                userData.skillOptions = new List<string>(Request.Cookies["Skills"].Split(Environment.NewLine));
                this.CoverLetter = userData.coverLetter;
            }

        }
        public void OnGet(string vacancyID)
        {
            GetUserData();
            if (userData.skillOptions.Count == 0) {
                Response.Redirect("Settings");
            }
            if (vacancyID != null && !vacancyID.Trim().Equals(""))
            {
                posting = new Posting(vacancyID);
                this.Posting_ID = vacancyID;
                this.CoverLetter = userData.coverLetter;
            }
        }
        public void OnPost()
        {
            GetUserData();
            string vacancyID = Request.Form["posting_id"];
            string coverLetterFormat = Request.Cookies["CoverLetter"];
            if (vacancyID != null && !vacancyID.Trim().Equals(""))
            {
                try
                {

                    posting = new Posting(vacancyID.Trim());
                    if (!string.IsNullOrEmpty(Request.Form["SkillCheckboxes"]))
                    {
                        this.CoverLetter = posting.GenerateLetter(coverLetterFormat, userData, Request.Form["SkillCheckboxes"]);
                    }
                    this.Posting_ID = vacancyID;
                }
                catch (Exception e)
                {
                    Console.WriteLine($"Vacancy ID {vacancyID} caused exception {e}");
                    _logger.LogError(e.ToString());
                }
            }
            else
            {
                _logger.LogDebug($"Unable to get Posting ID from form.");
            }

        }
    }
}