using CommonFunc;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EnvigoHiring.Models.Position
{
    public class PositionModel : BaseClass
    {
        public int PositionID { get; set; }
        [Required(ErrorMessage ="Alert! Select desgination")]
        public string ddlDesignation { get; set; }
       
        [Required(ErrorMessage = "Alert! Select department")]
        public string ddlDepartment { get; set; }
        [Required(ErrorMessage = "Alert! Select unit")]
        public string ddlUnit { get; set; }
        [Required(ErrorMessage = "Alert! Select priority")]
        public string ddlPriority { get; set; }
        public string TAT { get; set; }
        [Required(ErrorMessage = "Alert! Request Date should not be blank")]
        [DataType(DataType.DateTime,ErrorMessage ="Invalid Request date")]
        public string RequestDate { get; set; }
        [Required(ErrorMessage = "Alert! ClosedBy Date should not be blank")]
        public string ClosedByDate { get; set; }
        [Required(ErrorMessage = "Alert! Experience should be grater then 0")]
        public double Experience { get; set; }
       
        public double YearlySalaryBudget { get; set; }
        public string Status { get; set; }
        public List<SelectListItem> Designation { get; set; }
        public List<SelectListItem> Department { get; set; }
        public DataTable dtPosition { get; set; }
        
        DataLayer obj = DataLayer.Instance;

        public bool Filldata()
        {
            bool result = true;
            string query = string.Format("select * from tblPositions where PositionID={0}", PositionID);
            DataTable dt = obj.SelectDatatable(query);
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                ddlDesignation = BasicFunc.SetParamValue(row, "DesignationID");
                ddlDepartment = BasicFunc.SetParamValue(row, "Department");
                Experience = Convert.ToDouble(BasicFunc.SetParamValue(row, "Experience"));
                ddlUnit = BasicFunc.SetParamValue(row, "Unit");
                ddlPriority = BasicFunc.SetParamValue(row, "Priority");
                TAT = Convert.ToDateTime(BasicFunc.SetParamValue(row, "TAT")).ToString("MM/dd/yyyy");
                ClosedByDate = Convert.ToDateTime(BasicFunc.SetParamValue(row, "ClosedByDate")).ToString("MM/dd/yyyy");
                YearlySalaryBudget = Convert.ToDouble(BasicFunc.SetParamValue(row, "YearlySalaryBudget"));
                //chkActive = (BasicFunc.SetParamValue(row, "Status")=="1")?true:false;
                Status= BasicFunc.SetParamValue(row, "Status");
                
            }
            else
            {
                result = false;
                reset();
            }
            return result;
        }
        public void reset()
        {
            ddlDesignation = "0";
            Experience = 0;
            ddlDepartment = "0";
            ddlUnit = "0";
            ddlPriority = "0";
            TAT = "";
            ClosedByDate = "";
            YearlySalaryBudget = 0;
        }
        public int JobDescriptionStatus(string PosID)
        {
            int JDStatus = 0;
            string query = "Select ApproveStatus from tblJobDescription where PositionID=" + PosID;
            DataTable dt = obj.SelectDatatable(query);
            if (dt != null && dt.Rows.Count > 0)
            {
                JDStatus = BasicFunc.SetParamValue(dt.Rows[0], "ApproveStatus").ToInt32();
            }
            return JDStatus;
        }
        public void SaveData()
        {
            FilePath = ConfigurationManager.AppSettings["ResumePath"].ToString().Trim();
            var vl = ValidationFunc.ValidateModelData<PositionModel>(this, "ddlDesignation", "ddlRequester", "Experience","ddlDepartment", "ddlUnit", "ddlPriority", "YearlySalaryBudget");
            if (vl.isValid == false)
            {
                alert(vl.Message, vl.isValid);
                return;
            }
            if (!CheckFunc.IsDate(ClosedByDate))
            {
                alert("Alert! Closed By Date is not Valid date time", false);
            }
           
            var sv = Save();
            alert(sv.Message, sv.isSuccess);
        }
        //public validate ValidateData()
        //{
        //    validate vm = new validate();
        //    vm.isValid = true;
        //    /* Check Duplicate Page */
        //    string qryChkExist1 = "select EmailID from tblMasterCandidatePool where EmailID = '" + HttpUtility.HtmlEncode(EmailID.ToString().Trim()) + "'";
        //    if (PositionID != 0)
        //    {
        //        qryChkExist1 = "select EmailID from tblMasterCandidatePool where EmailID = '" + HttpUtility.HtmlEncode(EmailID.ToString().Trim()) + "' and CandidateID<>" + CandidateID;
        //    }
        //    string ChkRecord1 = obj.GetDatafromQuery(qryChkExist1)[0];
        //    if (ChkRecord1 != null)
        //    {
        //        if (ChkRecord1 != "")
        //        {
        //            vm.isValid = false;
        //            vm.Message = "Email  already exist! Please choose diffrent";
        //            return vm;
        //        }
        //    }


        //    return vm;
        //}
        public SaveData Save()
        {
            SaveData sv = new SaveData();

            //var vl = ValidateData();
            //sv.isSuccess = vl.isValid;
            //if (vl.isValid == false)
            //{
            //    sv.Message = vl.Message;
            //    return sv;
            //}
            Status=(PositionID > 0)? Status : "Open";
            SqlParameter[] perm1 = new SqlParameter[11];
            perm1[0] = new SqlParameter("@PositionID", PositionID);
            perm1[1] = new SqlParameter("@DesignationID", ddlDesignation.ToInt32());
            perm1[2] = new SqlParameter("@RequesterID", UserID.ToInt32());
            perm1[3] = new SqlParameter("@Department", ddlDepartment.ToInt32());
            perm1[4] = new SqlParameter("@Unit", ddlUnit.ToInt32());
            perm1[5] = new SqlParameter("@Priority", ddlPriority.HtmlEncode());
            perm1[6] = new SqlParameter("@TAT", GetTAT().ToString("MM/dd/yyyy"));
            perm1[8] = new SqlParameter("@ClosedByDate", ClosedByDate.ToString().Trim());
            perm1[9] = new SqlParameter("@Experience", Experience);
            perm1[10] = new SqlParameter("@YearlySalaryBudget", YearlySalaryBudget);
            perm1[7] = new SqlParameter("@Status", Status);
            DataTable success1 = obj.ExecuteStoreProcedure("proc_tblPositions", perm1);
            //CandidateID = Int32.Parse(perm1[19].Value.ToString().Trim());'@LastCompany', 
            if (success1 != null)
            {
                if (PositionID == 0)
                {
                    sv.isSuccess = true;
                    sv.Message = "<b>Success :</b> Page added successfully.";
                    //Send Mail
                   string emails =  CommonFunctions.getadminemailid(4);
                    if (emails.Length > 0)
                    {
                        string FileName = AppDomain.CurrentDomain.BaseDirectory + "content\\mailer.html";
                        System.IO.StreamReader ObjStrmRdr;
                        ObjStrmRdr = System.IO.File.OpenText(FileName);
                        string StrMail = ObjStrmRdr.ReadToEnd();
                        StrMail = StrMail.Replace("$$Heading$$", "New Position Posted!");
                        StrMail = StrMail.Replace("$$Content$$", "Dear Recruiter,<br/><br/> New position has been posted by "+ Users.LoginDetail().UserName.ToString().Trim() + " on <b>Envigo Hiring</b> application, Position TAT date is "+ GetTAT().ToString("MM/dd/yyyy") + ". <a href='" + ConfigurationManager.AppSettings["SiteUrl"] + "' target=_blank>Click here</a> to review.");
                        ObjStrmRdr.Close();
                        CommonFunctions.Email_Send("New Position Request - Envigo Hiring", emails, StrMail);
                    }
                    //End Send Email




                    return sv;
                }
                else
                {
                    sv.isSuccess = true;
                    sv.Message = "<b>Success :</b> Page updated successfully.";

                    //Send Mail
                    string emails = CommonFunctions.getadminemailid(4);
                    if (emails.Length > 0)
                    {
                        string FileName = AppDomain.CurrentDomain.BaseDirectory + "content\\mailer.html";
                        System.IO.StreamReader ObjStrmRdr;
                        ObjStrmRdr = System.IO.File.OpenText(FileName);
                        string StrMail = ObjStrmRdr.ReadToEnd();
                        StrMail = StrMail.Replace("$$Heading$$", "Existing Position updated!");
                        StrMail = StrMail.Replace("$$Content$$", "Dear Recruiter,<br/><br/> Existing position has been updated by " + Users.LoginDetail().UserName.ToString().Trim() + " on <b>Envigo Hiring</b> application, Position TAT date is " + GetTAT().ToString("MM/dd/yyyy") + ". <a href='" + ConfigurationManager.AppSettings["SiteUrl"] + "' target=_blank>Click here</a> to review.");
                        ObjStrmRdr.Close();
                        CommonFunctions.Email_Send("Existing Position Updated - Envigo Hiring", emails, StrMail);
                    }
                    //End Send Email


                    return sv;
                }
            }
            return sv;
        }
        public DateTime GetTAT()
        {
            DateTime TATdate= DateTime.Now.AddDays(30);
            if (ddlPriority == "High")
            {
                TATdate= DateTime.Now.AddDays(7);
            }
            else if (ddlPriority == "Medium")
            {
                TATdate= DateTime.Now.AddDays(15);
            }
            else if (ddlPriority == "Low")
            {
                TATdate= DateTime.Now.AddDays(30);
            }
            return TATdate;
        }
        public DataTable viewPosition()
        {
            string subquery = (Users.LoginDetail().Roles == "User") ? "and t.RequesterID=" + UserID.ToInt32() : "";
            string query = string.Format(@"select PositionID,DepartmentName,DesignationName,UnitName,Priority,TAT,ClosedByDate, t.status ,t.Experience,t.YearlySalaryBudget
                            ,(select count(1) from tblSuggestedApplicants where  positionid=t.positionid) as Tcount,u.username
							,(select count(1) from tblSuggestedApplicants where currentstatus='Approve' and positionid=t.positionid) as TApprvcount  from tblPositions t 
                            inner join  tblMasterDepartment dept on (t.Department=dept.DepartmentID) inner join tblMasterDesignation desg on (t.DesignationID=desg.DesignationID)
                            inner join tblMasterUnit unt on (t.Unit=unt.unitID) inner join tblUserLogin u on (t.RequesterID=u.UserID) where (t.status='Open' or t.status='ReOpen') {0} order by t.RequestDate desc", subquery);
            return obj.SelectDatatable(query);
        }
        public DataTable viewInActivePosition()
        {
            string subquery =(Users.LoginDetail().Roles=="User")? "and t.RequesterID="+UserID.ToInt32():"";
            string query = string.Format(@"select PositionID,DepartmentName,DesignationName,UnitName,Priority,TAT,ClosedByDate, t.status ,t.Experience,t.YearlySalaryBudget,
                             (select name from tblMasterCandidatePool where candidateID=t.SelectedCandidateID) as selectedCandidate
                            ,(select count(1) from tblSuggestedApplicants where currentstatus='selected' and positionid=t.positionid) as Tcount,u.username,t.Closure_Date
							,(select count(1) from tblSuggestedApplicants where currentstatus='Approve' and positionid=t.positionid) as TApprvcount  from tblPositions t 
                            inner join  tblMasterDepartment dept on (t.Department=dept.DepartmentID) inner join tblMasterDesignation desg on (t.DesignationID=desg.DesignationID)
                            inner join tblMasterUnit unt on (t.Unit=unt.unitID) inner join tblUserLogin u on (t.RequesterID=u.UserID) where (t.status!='Open' and t.status!='ReOpen') {0} order by t.RequestDate desc", subquery);
            return obj.SelectDatatable(query);
        }
        public List<SelectListItem> DesignationList(string DepartmentID)
        {
            DepartmentID = (DepartmentID == null || DepartmentID == "") ? "0" : DepartmentID;
            string query = string.Format("Select distinct DesignationID,DesignationName from tblMasterDesignation where departmentID={0} order by DesignationName asc", DepartmentID);
            return Common.FillSelectList(query, "DesignationName", "DesignationID");
        }

        public List<SelectListItem> DepartmentList()
        {
            string query = "Select distinct DepartmentID,DepartmentName from tblMasterDepartment order by DepartmentName asc";
            return Common.FillSelectList(query, "DepartmentName", "DepartmentID");
        }
        public List<SelectListItem> UnitList()
        {
            string query = "Select distinct unitID,UnitName from tblMasterUnit order by UnitName asc";
            return Common.FillSelectList(query, "UnitName", "unitID");
        }
       
        public List<SelectListItem> PriorityList()
        {
            return Common.FillSelectListManual("High","Medium","Low");
        }
        public List<SelectListItem> StatusList()
        {
            if (Status == "OnHold")
            {
                return Common.FillSelectListManual("OnHold", "ReOpen");
            }
            else if (Status == "ReOpen")
            {
                return Common.FillSelectListManual("ReOpen", "OnHold");
            }
            else
            {
                return Common.FillSelectListManual("Open", "OnHold");
            }
        }
    }
}