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.CandidatePool
{
    public class CandidateModel:BaseClass
    {
        public int CandidateID { get; set; }
        [Required(ErrorMessage ="Required! candidate Name should not be empty")]
        public string CandidateName { get; set; }
        [Required(ErrorMessage = "Required! Select gender")]
        public string Gender { get; set; }
        [Required(ErrorMessage = "Required! Candidate Experience should not be empty")]
        public Double Experience { get; set; }
        [RegularExpression(@"^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$", ErrorMessage = "Alert! Invalid email address!")]
        [Required(ErrorMessage = "Required! Email address should not be empty")]
        public string EmailID { get; set; }
        [Required(ErrorMessage = "Required! Contact Number should not be empty")]
        [RegularExpression(@"^[0-9]{10}$", ErrorMessage = "Alert! Contact no should be 10 didgit and Numeric!")]
        public string ContactNo { get; set; }
        [Required(ErrorMessage = "Required! Educartion should not be empty")]
        public string  Education { get; set; }
        [RegularExpression(@"^[0-9]{4}$", ErrorMessage = "Alert! Invalid passing year(2001)!")]
        [Required(ErrorMessage = "Required! Educartion should not be empty")]
        public int PassingYear { get; set; }
        [Required(ErrorMessage = "Required! select interested department")]
        public string ddlDepartment { get; set; }
        [AllowHtml]
        public string ProfessionalSummary { get; set; }
        public string LastCompany { get; set; }
        public string PrimaryIndustry { get; set; }
        public string PreviousNotableOrganisations { get; set; }
        [Required(ErrorMessage = "Required! Last Company should not be empty")]
        public string ddlCandidateStatus { get; set; }
        [Required(ErrorMessage = "Required! Source should not be empty")]
        public string Source { get; set; }
        [Required(ErrorMessage = "Required! Source date should not be empty")]
        public string SourcingDate { get; set; }
        public string LastContactedDate { get; set; }
        public string ResumeGoogleLink { get; set; }
        public string ResumeName { get; set; }
        public string SiteUrl { get; set; }
        [DataType(DataType.Upload)]
        public HttpPostedFileBase flResumeName { get; set; }
        public List<SelectListItem> DepartmentList { get; set; }
        public List<SelectListItem> CandidateStatus { get; set; }
        public List<SelectListItem> GenderList { get; set; }
        public DataTable dtCandidate { get; set; }
        public string SExperience { get; set; }
        DataLayer obj = DataLayer.Instance;
        public CandidateModel()
        {
            FilePath = ConfigurationManager.AppSettings["ResumePath"].ToString().Trim();
            SiteUrl = ConfigurationManager.AppSettings["SiteUrl"].ToString().Trim();
        }
        public bool Filldata()
        {
            bool result = true;
            string query = string.Format("select * from tblMasterCandidatePool where CandidateID={0}", CandidateID);
            DataTable dt = obj.SelectDatatable(query);
            if (dt != null && dt.Rows.Count > 0)
            {
                DataRow row = dt.Rows[0];
                CandidateName = BasicFunc.SetParamValue(row, "Name");
                EmailID = BasicFunc.SetParamValue(row, "EmailID");
                Experience = Convert.ToDouble(BasicFunc.SetParamValue(row, "Experience"));
                Education = BasicFunc.SetParamValue(row, "Education");
                ContactNo = BasicFunc.SetParamValue(row, "Phone");
                Gender = BasicFunc.SetParamValue(row, "Gender");
                PassingYear = Int32.Parse(BasicFunc.SetParamValue(row, "Year_of_Passing"));
                ddlDepartment = BasicFunc.SetParamValue(row, "InterestedDepartmentID");
                ProfessionalSummary = BasicFunc.SetParamValue(row, "ProfessionalSummary");
                LastCompany = BasicFunc.SetParamValue(row, "LastCompany");
                PrimaryIndustry = BasicFunc.SetParamValue(row, "PrimaryIndustry");
                PreviousNotableOrganisations = BasicFunc.SetParamValue(row, "PreviousNotableOrganisations");
                ddlCandidateStatus = BasicFunc.SetParamValue(row, "CandidateStatus");
                Source = BasicFunc.SetParamValue(row, "Source");
                SourcingDate = Convert.ToDateTime(BasicFunc.SetParamValue(row, "SourcingDate")).ToString("MM/dd/yyyy");
                LastContactedDate = BasicFunc.SetParamValue(row, "LastContactedDate");
                LastContactedDate = (LastContactedDate!=null && LastContactedDate!="")?Convert.ToDateTime(LastContactedDate).ToString("MM/dd/yyyy"):"";
                ResumeGoogleLink = BasicFunc.SetParamValue(row, "ResumeGoogleLink");
                ResumeName = BasicFunc.SetParamValue(row, "ResumeName");
            }
            else
            {
                result = false;
                reset();
            }
            return result;
        }
        public void reset()
        {
            CandidateName = "";
            EmailID = "";
            Experience = 0;
            Education = "";
            ContactNo = "";
            Gender = "";
            PassingYear = 0;
            ddlDepartment = "";
            ProfessionalSummary = "";
            LastCompany = "";
            PrimaryIndustry = "";
            PreviousNotableOrganisations = "";
            ddlCandidateStatus = "";
            Source = "";
            SourcingDate = "";
            LastContactedDate = "";
            ResumeGoogleLink = "";
            ResumeName = "";
        }

        public void SaveData()
        {
            
            var vl = ValidationFunc.ValidateModelData<CandidateModel>(this, "CandidateName","Gender","Experience","EmailID","ContactNo","Education","PassingYear","ddlDepartment","ProfessionalSummary","LastCompany","PrimaryIndustry","PreviousNotableOrganisations","CandidateStatus","Source","UserID");
            if (vl.isValid == false)
            {
                alert(vl.Message, vl.isValid);
                return;
            }
            if (!ResumeGoogleLink.IsLink() ||CheckFunc.IsLocalUrl(ResumeGoogleLink))
            {
                alert("Alert! Resume Googlr link is not correct", false);
                return;
            }
            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 (CandidateID != 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;
                }
            }

            /* Upload Banner Image */
            if (flResumeName != null)
            {
                ResumeName = (ResumeName != null && ResumeName != "") ? ResumeName : UploadFunc.CustomFileName(flResumeName,Users.LoginDetail().UserName);
                vm = UploadFunc.SaveFile(flResumeName, FilePath, ResumeName, ".pdf, .doc, .docx");
                if (!vm.isValid)
                {
                    return vm;
                }
            }
            if ((ResumeName == null || ResumeName == "") && (ResumeGoogleLink == null || ResumeGoogleLink == ""))
            {
                vm.isValid = false;
                vm.Message = "Alert! Please add Resume";
                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;
            }
            SqlParameter[] perm1 = new SqlParameter[21];
            perm1[0] = new SqlParameter("@CandidateID", CandidateID);
            perm1[1] = new SqlParameter("@Name", HttpUtility.HtmlEncode(CandidateName));
            perm1[2] = new SqlParameter("@gender", HttpUtility.HtmlEncode(Gender));
            perm1[3] = new SqlParameter("@Experience", Experience);
            perm1[4] = new SqlParameter("@EmailID", HttpUtility.HtmlEncode(EmailID));
            perm1[5] = new SqlParameter("@Education", HttpUtility.HtmlEncode(Education));
            perm1[6] = new SqlParameter("@Year_of_Passing", HttpUtility.HtmlEncode(PassingYear));
            perm1[7] = new SqlParameter("@InterestedDepartmentID", Int32.Parse(ddlDepartment));
            perm1[8] = new SqlParameter("@ProfessionalSummary", HttpUtility.HtmlEncode(ProfessionalSummary));
            perm1[9] = new SqlParameter("@PrimaryIndustry", HttpUtility.HtmlEncode(PrimaryIndustry));
            perm1[10] = new SqlParameter("@Phone", HttpUtility.HtmlEncode(ContactNo));
            perm1[11] = new SqlParameter("@PreviousNotableOrganisations", HttpUtility.HtmlEncode(PreviousNotableOrganisations));
            perm1[12] = new SqlParameter("@CandidateStatus", HttpUtility.HtmlEncode(ddlCandidateStatus));
            perm1[13] = new SqlParameter("@Source", HttpUtility.HtmlEncode(Source));
            perm1[14] = new SqlParameter("@SourcingDate", HttpUtility.HtmlEncode(SourcingDate));
            perm1[15] = new SqlParameter("@LastContactedDate", HttpUtility.HtmlEncode(LastContactedDate));
            perm1[16] = new SqlParameter("@ResumeGoogleLink", HttpUtility.HtmlEncode(ResumeGoogleLink));
            perm1[17] = new SqlParameter("@ResumeName", HttpUtility.HtmlEncode(ResumeName));
            perm1[18] = new SqlParameter("@addedby", Int32.Parse(UserID));
            perm1[19] = new SqlParameter("@nid", DbType.Int32);
            perm1[19].Direction = ParameterDirection.Output;
            perm1[20] = new SqlParameter("@LastCompany", HttpUtility.HtmlEncode(LastCompany));
            DataTable success1 = obj.ExecuteStoreProcedure("proc_tblMasterCandidatePool", perm1);
            //CandidateID = Int32.Parse(perm1[19].Value.ToString().Trim());'@LastCompany', 
            if (success1 != null)
            {
                if (CandidateID == 0)
                {
                    sv.isSuccess = true;
                    sv.Message = "<b>Success :</b> Page added successfully.";
                    
                }
                else
                {
                    sv.isSuccess = true;
                    sv.Message = "<b>Success :</b> Page updated successfully.";
                    
                }
            }
            else
            {
                sv.isSuccess = false;
                sv.Message = "<b>Error :</b> Please try again later.";
            }
            return sv;
        }
        public DataTable viewcandidate(string filter="")
        {
            string query = string.Format(@"select CandidateID,Name,Experience,EmailID,CandidateStatus,Source,Gender,ResumeName,ResumeGoogleLink,LastContactedDate,Education,DepartmentName from tblMasterCandidatePool t inner join 
                                        tblMasterDepartment t1 on(t.InterestedDepartmentID = t1.DepartmentID) where 1=1 {0}",filter);
            return obj.SelectDatatable(query);
        }
        public DataTable SearchCandidate()
        {
           string filter= SearchCondition();
           return viewcandidate(filter);
        }
        public string SearchCondition()
        {
            string filter = "";
            if (ddlDepartment != null && ddlDepartment != "")
            {
                filter += " and DepartmentName like '%" + ddlDepartment + "'%";
            }
            if (SExperience !=null && SExperience!="" && SExperience!="0")
            {
                filter += " and Experience like %" + SExperience + "%";
            }
            if (Gender != null && Gender != "")
            {
                filter += " and Gender like '%" + Gender + "%'";
            }
            if (Education != null && Education != "")
            {
                filter += " and Education like '%" + Education + "%'";
            }
            if (ddlCandidateStatus != null && ddlCandidateStatus != "")
            {
                filter += " and CandidateStatus like '%" + ddlCandidateStatus + "%'";
            }
            return filter;
        }
        public DataTable resetSearchCandidate()
        {
            return viewcandidate();
        }
        public void DownloadCandidate()
        {
            SiteUrl = SiteUrl.Substring(0, SiteUrl.Length - 1);
            string filter = SearchCondition();
            string query = string.Format(@"select CandidateID,Name,Experience,EmailID,Phone,Education,Year_of_Passing,DepartmentName as 'Department interested in',CandidateStatus,ProfessionalSummary,LastCompany,PrimaryIndustry,PreviousNotableOrganisations,Source,
                                        SourcingDate,UserName,Gender,LastContactedDate,'<a href=''{1}{2}'+ResumeName+'''>'+ResumeName+'</a>' as Resume,
                                        '<a href='''+ResumeGoogleLink+'''>'+ResumeGoogleLink+'</a>' as GoogleResumeLink,t.createdate,t.updatedate from tblMasterCandidatePool t inner join 
                                        tblMasterDepartment t1 on(t.InterestedDepartmentID = t1.DepartmentID) inner join tblUserLogin users on (t.addedby=users.UserID) where 1=1 {0}", filter,SiteUrl,FilePath);
            DataTable dt = obj.SelectDatatable(query);
            obj.ExporttoExcel(dt, "CandidateData" + DateTime.Now.Ticks);
        }
        public List<SelectListItem> LoadGender()
        {
            return Common.FillSelectListManual("Male", "Female", "TransGender");
        }
        public List<SelectListItem> LoadCandidateStatus()
        {
            return Common.FillSelectListManual("Working", "Non-Working");
        }
        public List<SelectListItem> LoadDepartment()
        {
            string Query = "Select DepartmentID,DepartmentName from tblMasterDepartment order by DepartmentID";
            return Common.FillSelectList(Query, "DepartmentName", "DepartmentID");
        }
        public List<SelectListItem> LoadSourceJob()
        {
            string Query = "Select SourceID,SourceName from tblMasterSource order by SourceID";
            return Common.FillSelectList(Query, "SourceName", "SourceID");
        }


    }
}