using System;
using System.Collections.Generic;
using System.Linq;

namespace Sevomin.Models.Repositories
{
    public class JobRepository:IJobRepository
    {
        
        #region Singleton
        private static JobRepository member;
        private static object locker = new object();

        private JobRepository()
        {
        }

        static JobRepository()
        {
              lock (locker)
              {
                  JobRepository.member = new JobRepository();
              }
        }
        public static JobRepository Current
        {
            get
            {
                return JobRepository.member;
            }

        }
        #endregion

        #region JobRepository

        public IQueryable<Job> ListAll()
        {
            return SevominDbContext.Current.Jobs;
        }

        public Job Find(long key)
        {
            return ListAll().SingleOrDefault(d => d.Id == key);
        }

        public void Delete(Job d)
        {
            SevominDbContext.Current.Jobs.Remove(d);
            Save();
        }

        public void Add(Job d)
        {
            SevominDbContext.Current.Jobs.Add(d);
            Save();
        }

        public void Save()
        {
            SevominDbContext.Current.SaveChanges();
        }

        public Job GetEmptyJobFor(Avalin avalin)
        {
            Job job = new Job();
            var parameters = ParameterRepository.Current.ListAll();

            job.JobParameters = new List<JobParameter>();
            
            foreach (var param in ParameterRepository.Current.ListAll())
            {
                JobParameter jp = new JobParameter(job, param);
                job.JobParameters.Add(jp);
            }
            job.IsFullTime = true;
            job.ShowCompanyLogo = false;
            job.ShowCompanyName = false;
            job.CreateDate = DateTime.UtcNow;
            job.Avalin = avalin;            
            avalin.Jobs.Add(job);
            return job;
        }

        public DovominJob Apply(Dovomin dovomin, Job job, string coverLetter)
        {
            DovominJob dj = new DovominJob(dovomin, job);
            dj.ApplyDate = DateTime.UtcNow;
            dj.CoverLetter = coverLetter;

            if (dovomin.DovominJobs.Any(d => d.JobId == job.Id))
            {
                dovomin.DovominJobs.First(d => d.JobId == job.Id).CoverLetter = coverLetter;
            }
            else
            {
                dovomin.DovominJobs.Add(dj);
            }

            Save();

            return dj;
        }
        #endregion        
    }
}
