using System;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;

namespace Sevomin.Models
{
    public class DovominJob
    {
        [Key]
        public long Id { get; set; }

        [Index("IX_DovominJobUniqueIndex", Order = 1, IsUnique = true)]
        [Required]
        [StringLength(128)]
        public string DovominId { get; set; }

        [Index]
        [Index("IX_DovominJobUniqueIndex", Order = 2, IsUnique = true)]
        [Required]
        public long JobId { get; set; }

        [Required]
        public DateTime ApplyDate { get; set; }
        
        public string CoverLetter { get; set; }

        public decimal Affinity { get; set; }

        public bool MinimumRequirement { get; set; }

        public DateTime? AvalinSeen { get; set; }

        public string AvalinComment { get; set; }

        public bool AvalinDelete { get; set; }

        public virtual Dovomin Dovomin { get; set; }
        public virtual Job Job { get; set; }

        public DovominJob(Dovomin dovomin, Job job)
        {
            this.Dovomin = dovomin;
            this.Job = job;
            CalculateAffinity();
        }

        public DovominJob()
        {
        }

        public void CalculateAffinity()
        {
            if (Dovomin == null || Job == null)
                return;

            MinimumRequirement = true;
            decimal sum = 0;
            decimal count = 0;
            Affinity = 0;
            foreach (var jp in 
                Job.JobParameters.Where(x=>x.Moscow != 0 && !string.IsNullOrWhiteSpace(x.StringValue) ))
            {
                count++;
                DovominParameter dp = Dovomin.DovominParameters.SingleOrDefault(x=>x.ParameterId == jp.ParameterId);
                if (dp == null)
                    continue;
                if (jp.Moscow == 4)
                {
                    if ((jp.StringValue != dp.StringValue && jp.NumericValue == 0)
                        || (jp.NumericValue > 0 && jp.NumericValue > dp.NumericValue))
                    {
                        MinimumRequirement = false;
                    }
                }                
                
                decimal? dpv = dp.NumericValue;
                decimal? jpv = jp.NumericValue;
                decimal m = jp.Moscow / 4;
                if (jpv == null)
                {
                    if (jp.StringValue == dp.StringValue)
                        sum +=  m;
                    continue;
                }
                if (dpv == null)
                    continue;
                if (jpv <= dpv)
                    sum += m;
                else
                    sum += m * ((jpv.Value - dpv.Value) / jpv.Value);
            }
            this.Affinity = sum / count;
        }
    }
}
