using AutoMapper;
using JobPortalAPI.DTOs;
using JobPortalAPI.Models;
using JobPortalAPI.UnitOfWork;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Build.Tasks.Deployment.Bootstrapper;
using Microsoft.EntityFrameworkCore;
using System.Xml.Linq;
using static System.Net.Mime.MediaTypeNames;


namespace JobPortalAPI.Controllers
{
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]

    [Route("api/[controller]")]
    [ApiController]
    public class CVsController : BaseController
    {
        private readonly IMapper _mapper;
        protected readonly JobPortalDBContext Context;
        private DbSet<Cv> _dbSet;

        public CVsController(IUnitOfWork unitOfWork, IMapper mapper, JobPortalDBContext context)
            : base(unitOfWork)
        {
            _mapper = mapper;
            Context = context;
            _dbSet = Context.Set<Cv>();
        }
        [HttpGet]
        public IActionResult GetAll()
        {
            var Cvs = _unitOfWork.CvRepo.GetAllCvsDetails();
            List<CvDto> cvDtos = new List<CvDto>();
            foreach (Cv v in Cvs)
            {
                CvDto CvDto = new CvDto();
                CvDto.Id = v.Id;
                CvDto.Stages = v.Stages;
                CvDto.Certificate = v.Certificate;
                CvDto.PreviousWorks = v.PreviousWorks;
                CvDto.Languages = v.Languages;
                var jobseeker = _unitOfWork.JobSeekerRepo.GetAllWithSpecification().FirstOrDefault(js => js.Id == v.Id);
                CvDto.SpecificationName = jobseeker.Specification.Name;
                CvDto.Birthdate = jobseeker.Birthdate;
                CvDto.Gender = jobseeker.Gender;
                var person = _unitOfWork.PersonRepo.Get(v.Id);
                CvDto.Email = person.Email;
                CvDto.Address = person.Address;
                CvDto.Name = person.Name;
                CvDto.Phone = person.Phone;
                //string currentDirectory = Directory.GetCurrentDirectory();
                var filePath = Path.Combine("Images", person.Image);
                //var fullPath = Path.Combine(currentDirectory, filePath);

                //byte[] myimage = System.IO.File.ReadAllBytes(fullPath);
                CvDto.Image = filePath;
                foreach (var item in v.Cvskills)
                {
                    SkillDto x = new SkillDto();
                    x.PracticePeriod = item.PracticePeriod;
                    var skill = _unitOfWork.SkillRepo.Get(item.SkillId);
                    x.SkillId = skill.Id;
                    x.Name = skill.Name;
                    if (x != null)
                    {
                        CvDto.skills.Add(x);

                    }
                    else
                    {

                    }
                }
                cvDtos.Add(CvDto);
            }
            return Ok(cvDtos);
        }
        [HttpGet("GetAllApplicants/{id}")]
        public IActionResult GetAllApplicants(int id)
        {
            var entryjobs = _unitOfWork.JobEntryRepo.GetAll().Where(e => e.JobId == id);
            List<CvDto> cvDtos = new List<CvDto>();
            foreach (JobEntry entry in entryjobs)
            {
                var v = _unitOfWork.CvRepo.GetAllCvDetails(entry.JobSeekerId);

                CvDto CvDto = new CvDto();
                CvDto.Id = v.Id;
                CvDto.Stages = v.Stages;
                CvDto.Certificate = v.Certificate;
                CvDto.PreviousWorks = v.PreviousWorks;
                CvDto.Languages = v.Languages;
                var jobseeker = _unitOfWork.JobSeekerRepo.GetAllWithSpecification().FirstOrDefault(js => js.Id == v.Id);
                CvDto.SpecificationName = jobseeker.Specification.Name;
                CvDto.Birthdate = jobseeker.Birthdate;
                CvDto.Gender = jobseeker.Gender;
                var person = _unitOfWork.PersonRepo.Get(v.Id);
                CvDto.Email = person.Email;
                CvDto.Address = person.Address;
                CvDto.Name = person.Name;
                CvDto.Phone = person.Phone;
                //string currentDirectory = Directory.GetCurrentDirectory();
                var filePath = Path.Combine("Images", person.Image);
                //var fullPath = Path.Combine(currentDirectory, filePath);

                //byte[] myimage = System.IO.File.ReadAllBytes(fullPath);
                CvDto.Image = filePath;
                foreach (var item in v.Cvskills)
                {
                    SkillDto x = new SkillDto();
                    x.PracticePeriod = item.PracticePeriod;
                    var skill = _unitOfWork.SkillRepo.Get(item.SkillId);
                    x.SkillId = skill.Id;
                    x.Name = skill.Name;
                    if (x != null)
                    {
                        CvDto.skills.Add(x);

                    }
                    else
                    {

                    }
                }
                cvDtos.Add(CvDto);
            }
            return Ok(cvDtos);
        }
        [HttpGet("id")]
        public async Task<IActionResult> GetCvDetailsAsync(int id )
        {
            var Cv = _unitOfWork.CvRepo.GetAllCvDetails(id);
            CvDto CvDto = new CvDto();
            CvDto.Id = id;
            CvDto.Stages = Cv.Stages;
            CvDto.Certificate = Cv.Certificate;
            CvDto.PreviousWorks = Cv.PreviousWorks;
            CvDto.Languages = Cv.Languages;
            var jobseeker = _unitOfWork.JobSeekerRepo.GetAllWithSpecification().FirstOrDefault(js => js.Id == id);
            CvDto.SpecificationName = jobseeker.Specification.Name;
            CvDto.Birthdate = jobseeker.Birthdate;
            CvDto.Gender = jobseeker.Gender;
            var person = _unitOfWork.PersonRepo.Get(id);
            CvDto.Email = person.Email;
            CvDto.Address = person.Address;
            CvDto.Name = person.Name;
            CvDto.Phone = person.Phone;
            var filePath = Path.Combine("Images", person.Image);
    
            CvDto.Image = filePath;
            foreach (var item in Cv.Cvskills)
            {
                SkillDto x = new SkillDto();
                x.PracticePeriod = item.PracticePeriod;
                var skill = _unitOfWork.SkillRepo.Get(item.SkillId);
                x.SkillId = skill.Id;
                x.Name = skill.Name;
                if(x != null)
                {
                    CvDto.skills.Add(x);

                }
                else
                {
                   
                }
            }

            return Ok(CvDto);
        }

        
        [HttpGet("GetCvSkills")]
        public IActionResult GetCvSkills()
        {
            var Cvs = _unitOfWork.CvSkillRepo.GetAll().ToList();

            return Ok(Cvs);
        }
     
        [HttpPost("AddSkill/{id}")]
        public IActionResult AddSkill(int id , CvSkillDto skill )
        {
           if(ModelState.IsValid)
            {
                Boolean y = false;
                var Cv = _unitOfWork.CvRepo.Get(id);

                Cvskill cvskill = new Cvskill();
                cvskill.Cvid = Cv.Id;
                cvskill.PracticePeriod = skill.PracticePeriod;
                var sk = _unitOfWork.SkillRepo.GetAll().FirstOrDefault(s => s.Name.ToUpper().Contains(skill.Name.ToUpper()));
                if (sk == null)
                {
                    Skill skl = new Skill()
                    {

                        Name = skill.Name.ToUpper()
                    };
                    _unitOfWork.SkillRepo.Add(skl);
                    _unitOfWork.SaveChanges();
                    cvskill.SkillId = skl.Id;
                    _unitOfWork.CvSkillRepo.Add(cvskill);
                    _unitOfWork.SaveChanges();
                }
                else
                {
                    var x = _unitOfWork.CvSkillRepo.GetAll().FirstOrDefault(cs => cs.Cvid == id && cs.SkillId == sk.Id);
                    if (x == null)
                    {
                        cvskill.SkillId = sk.Id;
                        _unitOfWork.CvSkillRepo.Add(cvskill);
                        _unitOfWork.SaveChanges();

                    }
                    else
                    {
                        x.PracticePeriod = skill.PracticePeriod;
                        _unitOfWork.CvSkillRepo.Update(x);
                        _unitOfWork.SaveChanges();
                        y = true;

                    }

                }



                if (y == false)
                {
                    return Ok();
                }
                else
                {
                    return Ok("The skills are added, but there were skills were already exist so just updated the practice period !!!");
                }
            }
           else
            {
                return BadRequest(new AuthResult() { Errors = new List<string>() { "Enter valid values" } });
            }
        }

        [HttpPut("UpdateSkill/{id}")]
        public IActionResult UpdateSkill(int id, SkillDto skillDto)
        {
           if(ModelState.IsValid)
            {
                var cvskill = _unitOfWork.CvSkillRepo.GetAll().FirstOrDefault(cs => cs.Cvid == id && cs.SkillId == skillDto.SkillId);
                cvskill.PracticePeriod = skillDto.PracticePeriod;
                var skill = _unitOfWork.SkillRepo.GetAll().FirstOrDefault(s => s.Name.ToUpper().Contains(skillDto.Name.ToUpper()));
                if (skill == null)
                {
                    Skill sk = new Skill()
                    {
                        Name = skillDto.Name.ToUpper(),
                    };
                    _unitOfWork.SkillRepo.Add(sk);
                    _unitOfWork.SaveChanges();
                    cvskill.SkillId = sk.Id;
                    _unitOfWork.CvSkillRepo.Update(cvskill);
                    _unitOfWork.SaveChanges();
                    return Ok(skillDto);
                }
                else
                {
                    cvskill.SkillId = skill.Id;
                    _unitOfWork.CvSkillRepo.Update(cvskill);
                    _unitOfWork.SaveChanges();
                    return Ok(skillDto);
                }
            }
            else
            {
                return BadRequest(new AuthResult() { Errors = new List<string>() { "Enter valid values" } });
            }
          
        }
        [HttpDelete("DeleteSkill/{id}")]
        public IActionResult DeleteSkill(int id, int skillid)
        {
            var cvskill = _unitOfWork.CvSkillRepo.GetAll().FirstOrDefault(cs => cs.Cvid == id && cs.SkillId == skillid);
            _unitOfWork.CvSkillRepo.Remove(cvskill);
            _unitOfWork.SaveChanges();
            return Ok();
          

        }
    }
}
