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

namespace EnvigoHiring.Models.Applicants
{
    public class ApplicantsDetail : BaseClass
    {
        public int CandidateID { get; set; }
        public int PositionID { get; set; }
        public int ApplicantID { get; set; }
        public string Applicant { get; set; }
        public string Position { get; set; }
        public string Email { get; set; }
        public string ContactNo { get; set; }
        [Required(ErrorMessage ="Alert! Notice period should not be empty")]
        public int NoticePeriod { get; set; }
        [Required(ErrorMessage = "Alert! Current Salary should not be empty")]
        public double CurrentSalary { get; set; }
        public double ExpectedSalary { get; set; }
        public double Hikepercentage { get; set; }
        public string LastAppraised { get; set; }
        public string ddlBuyOut { get; set; }
        public double BuyOutCost { get; set; }
        public string ddlInterviewRound { get; set; }
        public string Interviewdate { get; set; }
        public string Interviewer { get; set; }
        public string ddlInterviewStage { get; set; }
        public bool HideInterview { get; set; }
        public DataTable dtApplicant { get; set; }
        DataLayer obj = DataLayer.Instance;

        public bool FillData()
        {
            bool result = false;
            HideInterview = false;
            string query = string.Format(@"Select cand.Name,pos.RequesterID,pos.DesignationName,cand.EmailID,cand.Phone,apl.*,round.RoundType,round.Interviewer
                            ,round.SheduledOn,apl.Stage from tblSuggestedApplicants sa left outer join tblApplicants apl on (sa.Candidate=apl.CandidateID)
                            left outer join tblInterviewRounds round on (apl.ApplicantID=round.ApplicantID)
                            inner join vwPosition pos on (sa.PositionID=pos.PositionID) inner join tblMasterCandidatePool cand on 
                            (sa.Candidate=cand.CandidateID) where sa.CurrentStatus='Approve' and sa.Candidate={0} and sa.PositionID={1} order by round.roundtype desc", CandidateID, PositionID);
            DataTable dt = obj.SelectDatatable(query);
            if (dt != null && dt.Rows.Count > 0)
            {
                result = true;
                DataRow row = dt.Rows[0];
                Applicant = row.SetParamValue("Name");
                Position = row.SetParamValue("DesignationName");
                Email = row.SetParamValue("EmailID");
                ContactNo = row.SetParamValue("Phone");
                NoticePeriod = row.SetParamValue("NoticePeriodDays").ToInt32();
                CurrentSalary = row.SetParamValue("CurrentSalary").ToDouble();
                ExpectedSalary = row.SetParamValue("ExpectedSalary").ToDouble();
                Hikepercentage = row.SetParamValue("RaisePercentage").ToDouble();
                LastAppraised = row.SetParamValue("Last_Appraised_On");
                ddlBuyOut = row.SetParamValue("IsBuyout");
                BuyOutCost = row.SetParamValue("BuyoutCost").ToDouble();
                ddlInterviewRound = row.SetParamValue("Stage");
                Interviewdate = row.SetParamValue("SheduledOn").ToDateTime().ToString("MM/dd/yyyy hh:mm");
                Interviewer = row.SetParamValue("Interviewer");
                ddlInterviewStage = row.SetParamValue("Stage");
                if (ddlInterviewRound!="")
                {
                    HideInterview = true;
                }
            }
            return result;
        }

        public void SaveData()
        {
            var sv = Save();
            alert(sv.Message, sv.isSuccess);
        }

        public validate ValidateData()
        {
            validate vm = new validate();
            vm = ValidationFunc.ValidateModelData<ApplicantsDetail>(this, "NoticePeriod", "CurrentSalary", "ExpectedSalary",
               "Hikepercentage", "LastAppraised", "ddlBuyOut", "BuyOutCost", "ddlInterviewRound", "Interviewdate", "Interviewer");
            if (HideInterview==false && !CommonFunctions.IsDate(Interviewdate))
            {
                vm.isValid = false;
                vm.Message = "Alert! Interview date is datetime type";
            }
            if (ExpectedSalary == 0 && Hikepercentage == 0)
            {
                vm.isValid = false;
                vm.Message = "Alert! Fill either excpected salary or hike percentage";
            }
            
            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;
            }
            if (ExpectedSalary > 0)
            {
                Hikepercentage = (ExpectedSalary * 100 / CurrentSalary)-100;
            }
            else
            {
                ExpectedSalary = CurrentSalary * (100 + Hikepercentage) / 100;
            }
            ddlInterviewStage = (ddlInterviewStage.ToInt32() == 0) ? "1" : ddlInterviewStage;
            SqlParameter[] perm1 = new SqlParameter[14];
            perm1[0] = new SqlParameter("@CandidateID", CandidateID);
            perm1[1] = new SqlParameter("@PositionID", PositionID);
            perm1[2] = new SqlParameter("@NoticePeriodDays", NoticePeriod);
            perm1[3] = new SqlParameter("@UserID", UserID);
            perm1[4] = new SqlParameter("@CurrentSalary", CurrentSalary);
            perm1[5] = new SqlParameter("@ExpectedSalary", ExpectedSalary);
            perm1[6] = new SqlParameter("@RaisePercentage", Hikepercentage);
            perm1[7] = new SqlParameter("@Last_Appraised_On", LastAppraised);
            perm1[8] = new SqlParameter("@IsBuyout", ddlBuyOut);
            perm1[9] = new SqlParameter("@BuyoutCost", BuyOutCost);
            perm1[10] = new SqlParameter("@interviewType", ddlInterviewRound);
            perm1[11] = new SqlParameter("@interviewer", Interviewer);
            perm1[12] = new SqlParameter("@interviewdate", Interviewdate.ToDateTime());
            perm1[13] = new SqlParameter("@Stage", ddlInterviewStage.ToInt32());
            DataTable success1 = obj.ExecuteStoreProcedure("proc_tblApplicants", perm1);
            //CandidateID = Int32.Parse(perm1[19].Value.ToString().Trim());'@LastCompany', 
            if (success1 != null)
            {
                    sv.isSuccess = true;
                    sv.Message = "<b>Success :</b> Applicant updated successfully.";
            }
            else
            {
                sv.isSuccess = false;
                sv.Message = "<b>Error :</b> Please try again later.";
            }
            alert(sv.Message, sv.isSuccess);
            return sv;
        }

        public List<SelectListItem> InterviewerList()
        {
            string Query = "Select UserName, UserID from tblUserLogin where Role in (1,3) and status=1";
            return Common.FillSelectList(Query, "UserName", "UserID");
        }
        public List<SelectListItem> BuyOutList()
        {
            return Common.FillSelectListManual("Yes", "No", "Not Sure");
        }
        public List<SelectListItem> InterviewType()
        {
            return Common.FillSelectListManual("Telephonic", "F2F");
        }
        public List<SelectListItem> IntervieweStageList()
        {
            string Query = "Select StatusName, HiringID from tblMasterHiringStatus order by HiringID";
            return Common.FillSelectList(Query, "StatusName", "HiringID");
        }
        public DataTable DisplayApplicants(int id=0)
        {
            FilePath = ConfigurationManager.AppSettings["ResumePath"].ToString().Trim();
            string Subquery=(id>0)?" where t.candidateID="+id:"";
            string query = string.Format(@"select cand.Name,t.positionid,cand.EmailID,cand.Phone,cand.ResumeGoogleLink,cand.ResumeName,t.NoticePeriodDays,pos.DesignationName,pos.UnitName,Pos.Status,ir.Result as InterViewResult,t1.*,
                            users.UserName as InterviewerName,(select StatusName from tblMasterHiringStatus where HiringID=t.stage) as CStage from tblApplicants t left outer join tblInterviewRounds t1 on (t.ApplicantID=t1.ApplicantID)
                            inner join tblMasterCandidatePool cand on (t.CandidateID=cand.CandidateID) inner join vwPosition pos on (t.PositionID=pos.PositionID)
							left outer join tblUserLogin users on (t1.Interviewer=users.UserID) left outer join tblMasterInterviewResult ir on (t1.InterViewresult=ir.StatusID) {0} order by t1.SheduledOn desc, t1.RoundType desc",Subquery);
            return obj.SelectDatatable(query);
        }
        public DataTable DisplayApplicantsByPosition(int id = 0)
        {
            FilePath = ConfigurationManager.AppSettings["ResumePath"].ToString().Trim();
            string Subquery = (id > 0) ? " where t.positionID=" + id : "";
            string query = string.Format(@"select cand.Name,t.positionid,cand.EmailID,cand.Phone,cand.ResumeGoogleLink,cand.ResumeName,t.NoticePeriodDays,pos.DesignationName,pos.UnitName,Pos.Status,ir.Result as InterViewResult,(select count(1) from tblSuggestedApplicants where positionid=t.PositionID and candidate=t.CandidateID) as SuggestedApplicantCount,
                            (Select count(1) from tblInterviewRounds where ApplicantID!=t1.ApplicantID and candidateid=t1.candidateID and SheduledOn>t1.SheduledOn) as NewInterview,t1.*,intstatus.Statusname as InterViewStatusname, users.UserName as InterviewerName,(select StatusName from tblMasterHiringStatus 
                            where HiringID=t.stage) as CStage from tblApplicants t left outer join tblInterviewRounds t1 on (t.ApplicantID=t1.ApplicantID) inner join tblMasterCandidatePool cand on (t.CandidateID=cand.CandidateID) inner join vwPosition pos on (t.PositionID=pos.PositionID)
							left outer join tblUserLogin users on (t1.Interviewer=users.UserID) left outer join tblMasterInterviewResult ir on (t1.InterViewresult=ir.StatusID)
							left outer join tblMasterInterviewStatus intstatus on (t1.InterviewStatus=intstatus.InterviewStatusID)  {0} order by t1.SheduledOn desc, t1.RoundType desc", Subquery);
            return obj.SelectDatatable(query);
        }

        public void ActivatereOpenApplicant(int ApplicantID)
        {
            SaveData sv = new SaveData();
            SqlParameter[] perm1 = new SqlParameter[2];
            perm1[0] = new SqlParameter("@PositionID", PositionID);
            perm1[1] = new SqlParameter("@ApplicantID", ApplicantID);
            DataTable success1 = obj.ExecuteStoreProcedure("proc_tblSuggestedApplicants_ReOpen", perm1);
            if (success1 != null)
            {
                sv.isSuccess = true;
                sv.Message = "<b>Success :</b> Candidate activated successfully.";
            }
            else
            {
                sv.isSuccess = false;
                sv.Message = "<b>Error :</b> Please try again later.";
            }
            alert(sv.Message, sv.isSuccess);
        }

    }
}