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.Identity;
using Microsoft.AspNetCore.Mvc;

namespace JobPortalAPI.Controllers
{
    [Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
    [Route("api/[controller]")]
    [ApiController]
    public class CompaniesController : BaseController
    {
        private readonly UserManager<IdentityUser> _userManager;
        private readonly IConfiguration _configuration;

        private readonly IMapper _mapper;
        public CompaniesController(IUnitOfWork unitOfWork, IMapper mapper, UserManager<IdentityUser> userManager, IConfiguration configuration)
            : base(unitOfWork)
        {
            _mapper = mapper;
            _userManager = userManager;
            _configuration = configuration;
        }
        [HttpGet]
        public IActionResult GetCompanies()
        {

            var x = _unitOfWork.CompanyRepo.GetCompaniesDetails();
            if (x != null)
            {
                List<CompanyDto> CompanyDtos = new List<CompanyDto>();
                foreach (var company in x)
                {
                    CompanyDto companyDto = new CompanyDto();
                    companyDto.Address = company.IdNavigation.Address;
                    companyDto.Id = company.IdNavigation.Id;
                    var filePath = Path.Combine("Images", company.IdNavigation.Image);
                    companyDto.Image = filePath;
                    companyDto.Phone = company.IdNavigation.Phone;
                    companyDto.Email = company.IdNavigation.Email;
                    companyDto.Description = company.Description;
                    companyDto.Name = company.IdNavigation.Name;
                    CompanyDtos.Add(companyDto);
                }
                return Ok(CompanyDtos);
            }
            else
            {
                return Ok("No companies exist!!!");
            }
        }
        [HttpGet("id")]
        public IActionResult GetCompany(int id)
        {

            var x = _unitOfWork.CompanyRepo.GetCompaniesDetails().FirstOrDefault(c => c.Id == id);
            if (x != null)
            {

                CompanyDto companyDto = new CompanyDto();
                companyDto.Address = x.IdNavigation.Address;
                companyDto.Id = x.IdNavigation.Id;
                //string currentDirectory = Directory.GetCurrentDirectory();
                var filePath = Path.Combine("Images", x.IdNavigation.Image);
                //var fullPath = Path.Combine(currentDirectory, filePath);
                //byte[] myimage = System.IO.File.ReadAllBytes(fullPath);
                companyDto.Image = filePath;
                companyDto.Phone = x.IdNavigation.Phone;
                companyDto.Email = x.IdNavigation.Email;
                companyDto.Description = x.Description;
                companyDto.Name = x.IdNavigation.Name;

                return Ok(companyDto);
            }
            else
            {
                return Ok("this company doesn't exist!!!");
            }
        }
        [HttpGet("GetCompanyNameById/id")]
        public IActionResult GetCompanyNameById(int id)
        {

            var x = _unitOfWork.PersonRepo.Get(id);
            if (x != null)
            {
                String name;
                name = x.Name;
                return Ok(name);
            }
            else
            {
                return Ok("this company doesn't exist!!!");
            }
        }
        [AllowAnonymous]
        [HttpPost]
        public async Task<IActionResult> RegiserAsync([FromForm] PersonCompanyDto dto)
        {
            if (ModelState.IsValid)
            {
                var user_exist = await _userManager.FindByEmailAsync(dto.Email);
                if (user_exist != null)
                {
                    return BadRequest
                    (
                         new AuthResult()
                         {
                             Errors = new List<string>()
                            {
                                "Email already exist"
                            }

                         }
                    );
                }
                if (!CheckPhoneNumber(dto.Phone))
                {
                    return BadRequest(new AuthResult() { Errors = new List<string>() { "Enter a valid phone number" } });
                }
                var userid = Guid.NewGuid().ToString();
                var new_user = new IdentityUser()
                {
                    Email = dto.Email,
                    UserName = $"{dto.Name}{userid}"

                };
                var is_created = await _userManager.CreateAsync(new_user, dto.Password);
                if (!(is_created.Succeeded))
                {
                    return BadRequest(
                          new AuthResult()
                          {
                              Errors = new List<string>()
                            {
                                "Enter valid values"
                            }

                          }
                        );
                }
                var person = _mapper.Map<Person>(dto);
                var company = _mapper.Map<Company>(dto);
                string currentDirectory = Directory.GetCurrentDirectory();

                if (dto.Image != null && dto.Image.Length > 0)
                {

                    var fileName = Guid.NewGuid().ToString() + Path.GetExtension(dto.Image.FileName);
                    var filePath = Path.Combine("Images", fileName);
                    var fullfilePath = Path.Combine("wwwroot", filePath);
                    var fullPath = Path.Combine(currentDirectory, fullfilePath);
                    using (var stream = new FileStream(fullPath, FileMode.Create))
                    {
                        dto.Image.CopyTo(stream);
                    }
                    person.Image = fileName;

                }

                else
                {
                    return BadRequest(
                          new AuthResult()
                          {
                              Errors = new List<string>()
                            {
                                "Image is required"
                            }

                          });

                }
                company.IdNavigation = person;
                _unitOfWork.PersonRepo.Add(person);
                _unitOfWork.CompanyRepo.Add(company);
                _unitOfWork.SaveChanges();

                return Ok();
            }
            else
            {
                return BadRequest(
                      new AuthResult()
                      {
                          Errors = new List<string>()
                            {
                                "Enter valid values"
                            }

                      }
                    );
            }

        }
        [HttpPut("id")]
        public async Task<IActionResult> UpdateAsync(int id, [FromForm] UpdateCompanyDto dto)
        {
            if (ModelState.IsValid)
            {

                var person = _unitOfWork.PersonRepo.Get(id);
                var company = _unitOfWork.CompanyRepo.Get(id);


                if (company == null || person == null)
                {
                    return NotFound();
                }
                else
                {
                    var user = await _userManager.FindByEmailAsync(person.Email);
                    if (user != null)
                    {

                        await _userManager.SetEmailAsync(user, dto.Email);
                    }
                    string currentDirectory = Directory.GetCurrentDirectory();
                    var currentImage = person.Image;
                    var currentImagePath = Path.Combine("Images", person.Image);
                    var fullcurrentImagePath = Path.Combine("wwwroot", currentImagePath);

                    var currentImagefullPath = Path.Combine(currentDirectory, fullcurrentImagePath);                    person.Address = dto.Address;
                    person.Email = dto.Email;
                    person.Phone = dto.Phone;
                    person.Name = dto.Name;

                    if (dto.Image != null && dto.Image.Length > 0)
                    {
                        var fileName = Guid.NewGuid().ToString() + Path.GetExtension(dto.Image.FileName);
                        var filePath = Path.Combine("Images", fileName);
                        var fullfilePath = Path.Combine("wwwroot", filePath);
                        var fullPath = Path.Combine(currentDirectory, fullfilePath);
                        using (var stream = new FileStream(fullPath, FileMode.Create))
                        {
                            dto.Image.CopyTo(stream);
                        }
                        if (!string.IsNullOrEmpty(fullcurrentImagePath) && System.IO.File.Exists(fullcurrentImagePath))
                        {
                            System.IO.File.Delete(fullcurrentImagePath);
                        }
                        person.Image = fileName;

                    }
                    else if (!string.IsNullOrEmpty(currentImage))
                    {
                        person.Image = currentImage;
                    }
                    _unitOfWork.PersonRepo.Update(person);
                    _unitOfWork.SaveChanges();
                    company.Description = dto.Description;
                    _unitOfWork.CompanyRepo.Update(company);
                    _unitOfWork.SaveChanges();


                    return Ok();

                }


            }
            else
            {
                return BadRequest(new AuthResult() { Errors = new List<string>() { "Enter valid values" } });
            }

        }
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            var company = _unitOfWork.CompanyRepo.Get(id);
            var person = _unitOfWork.PersonRepo.Get(id);

            if (company == null || person == null)
            {
                return NotFound();
            }
            string currentDirectory = Directory.GetCurrentDirectory();
            var currentImage = person.Image;
            var currentImagePath = Path.Combine("Images", person.Image);
            var fullcurrentImagePath = Path.Combine("wwwroot", currentImagePath);

            var currentImagefullPath = Path.Combine(currentDirectory, fullcurrentImagePath);
            if (!string.IsNullOrEmpty(currentImagefullPath) && System.IO.File.Exists(currentImagefullPath))
            {
                System.IO.File.Delete(currentImagefullPath);
            }
            List<Job> joblist = new List<Job>();
            joblist = _unitOfWork.JobRepo.GetAll().Where(j => j.CompanyId == id).ToList();
            foreach (var job in joblist)
            {
                var jobskillslist = _unitOfWork.JobSkillRepo.GetAll().Where(js => js.JobId == job.Id);
                foreach (var jobskill in jobskillslist)
                {
                    _unitOfWork.JobSkillRepo.Remove(jobskill);
                    _unitOfWork.SaveChanges();
                }
                _unitOfWork.JobRepo.Remove(job);
                _unitOfWork.SaveChanges();
            }
            _unitOfWork.CompanyRepo.Remove(company);
            _unitOfWork.PersonRepo.Remove(person);
            _unitOfWork.SaveChanges();
            return Ok();
        }

        bool CheckPhoneNumber(String phonenumber)
        {
            bool x;
            if (phonenumber.Length == 10)
            {
                if (phonenumber[0] == '0' && phonenumber[1] == '9')
                {
                    x = true;
                    return x;
                }
                else
                {
                    x = false;
                    return x;
                }
            }
            else
            {
                x = false;
                return x;
            }
        }
    }

}
