public static Inspection AddComment(
     int InspectionId,
     string Comment,
     UserAccess ua)
 {
     Comment = Comment.Trim();
     if (ua.current_access == UserAccess.access_type.public_access)
     {
         return(null);
     }
     else
     {
         string sp = "dbo.add_inspection_comment";
         var    dp = new DynamicParameters();
         dp.Add("@Username", ua.display_name);
         dp.Add("@InspectionId", InspectionId);
         dp.Add("@FirstComment", Comment);
         int i;
         try // This function is for stored procedures
         {
             string cs = Constants.Get_ConnStr("WATSC" + (Constants.UseProduction() ? "Prod" : "QA"));
             using (IDbConnection db = new SqlConnection(cs))
             {
                 i = db.Execute(sp, dp, commandType: CommandType.StoredProcedure);
             }
         }
         catch (Exception ex)
         {
             Constants.Log(ex, "");
             i = 0;
         }
         //int i = Constants.Exec_Query_SP(sp, dp);
         if (i == -1)
         {
             Inspection isnp = Get(InspectionId);
             return(isnp);
         }
         else
         {
             return(null);
         }
     }
 }
        public List <string> Save(UserAccess ua)
        {
            List <InspType> inspTypes = InspType.GetCachedInspectionTypes();
            List <string>   errors    = this.Validate(ua.current_access, inspTypes);

            if (errors.Count > 0)
            {
                return(errors);
            }

            int    IRID           = this.AddIRID();
            string InitialComment = $"Inspection Request scheduled for {this.SchecDateTime.Date.ToShortDateString()}.";

            var dbArgs = new Dapper.DynamicParameters();

            dbArgs.Add("@PermitNo", this.PermitNo);
            dbArgs.Add("@InspCd", this.InspectionCd);
            dbArgs.Add("@SelectedDate", this.SchecDateTime.Date);
            dbArgs.Add("@Username", ua.user_name.Trim(), dbType: DbType.String, size: 7);
            dbArgs.Add("@DisplayName", ua.display_name);
            dbArgs.Add("@IRID", (IRID == -1) ? null : IRID.ToString());
            dbArgs.Add("@InitialComment", InitialComment);
            dbArgs.Add("@Comment", Comment);
            dbArgs.Add("@SavedInspectionID", -1, dbType: DbType.Int32, direction: ParameterDirection.Output, size: 8);

            string sql = $@"
      USE WATSC;     

      WITH last_completed_inspection_of_this_type AS (
  
        SELECT TOP 1
          BaseId,
          inspreqid,
          ResultADC
        FROM bpINS_REQUEST
        where inspectionCode = @InspCd
          AND PermitNo = @PermitNo
        order by inspreqid desc

      )

      INSERT INTO bpINS_REQUEST
          (PermitNo,
          InspectionCode,
          Inspector,
          SchecDateTime,
          ReqDateTime,
          BaseId,
          ReceivedBy,
          PrivProvIRId,
          ReinspectionId)
      SELECT TOP 1
          @PermitNo,
          @InspCd,
          CASE WHEN @IRId IS NOT NULL THEN 'PPI' ELSE NULL END inspector,
          CAST(@SelectedDate AS DATE), 
          GETDATE(),
          B.BaseId,
          @Username,
          @IRID,
          CASE WHEN L.ResultADC IN ('D','N') THEN L.InspReqID ELSE NULL END ReinspectionId
      FROM bpBASE_PERMIT B
      LEFT OUTER JOIN bpMASTER_PERMIT M ON M.BaseID = B.BaseID
      LEFT OUTER JOIN bpASSOC_PERMIT A ON B.BaseID = A.BaseID
      LEFT OUTER JOIN last_completed_inspection_of_this_type L ON L.BaseId = B.BaseID
      WHERE (A.PermitNo = @PermitNo OR M.PermitNo = @PermitNo)


      SET @SavedInspectionID = SCOPE_IDENTITY();

      EXEC add_inspection_comment @DisplayName, @SavedInspectionID, @InitialComment, @Comment;";

            try
            {
                //bool isFinal = (from it in inspTypes
                //                where it.InspCd == this.InspectionCd
                //                select it.Final).First();
                //Console.WriteLine("isFinal:", isFinal);


                var i = Constants.Exec_Query(sql, dbArgs);
                if (i > -1)
                {
                    int SavedInspectionId = dbArgs.Get <int>("@SavedInspectionID");


                    string inspDesc = (from it in inspTypes
                                       where it.InspCd == this.InspectionCd
                                       select it.InsDesc).First();
                    errors.Add(inspDesc + " inspection has been scheduled for permit #" + this.PermitNo + ", on " + this.SchecDateTime.ToShortDateString() + ". This was saved with request id " + SavedInspectionId + ".");
                }
                else
                {
                    errors.Add("No Record Saved, Please Try again. Contact the Building department if issues persist.");
                }
            }
            catch (Exception ex)
            {
                Constants.Log(ex, sql);
                errors.Add("No Record Saved, Please Try again. Contact the Building department if issues persist.");
            }
            return(errors);
        }
        private bool Validate(string PermitNumber, Inspection currentInspection, string ResultCode, string UserRemarks, UserAccess User)
        {
            if (User.current_access == UserAccess.access_type.contract_access)
            {
                List <Inspector> inspList = Inspector.GetCached();

                var inspectors = (from i in inspList
                                  where i.NTUsername == User.user_name
                                  select i).ToList();
                if (inspectors.Count() == 0)
                {
                    Errors.Add("Inspector not found.");
                }
                if (inspectors.First().Name != currentInspection.InspectorName)
                {
                    Errors.Add("This inspection is not assigned to this inspector.");
                }
            }
            if (PermitNumber != PermitNo)
            {
                Errors.Add("The permit number does not match the inspection, please check your request and try again.");
                return(false);
            }
            switch (ResultCode.Trim())
            {
            case "A":
            case "": // result is not set
            case "D":
            case "P":
            case "N":
                // only inspectors can change the result
                if (User.current_access == UserAccess.access_type.public_access)
                {
                    Errors.Add("Unauthorized Access.");
                    return(false);
                }

                if (ResultCode == "A" || ResultCode == "D")
                {
                    if (PrivateProviderInspectionRequestId > 0)
                    {
                        Errors.Add("Private provider inspections must be marked as Not Performed or Performed.");
                        return(false);
                    }
                }

                // If they are trying to change something that was completed before today.
                if (currentInspection.ResultADC != "" &&
                    InspDateTime != DateTime.MinValue.Date &&
                    InspDateTime.Date < DateTime.Today.AddDays(-2).Date)
                {
                    Errors.Add("Inspections completed more than two days ago cannot be changed.");
                    return(false);
                }
                if (currentInspection.ResultADC != "" &&
                    InspDateTime != DateTime.MinValue.Date &&
                    User.current_access == UserAccess.access_type.contract_access)
                {
                    Errors.Add("Completed inspections cannot be changed. Please contact the Building departent for assistance.");
                    return(false);
                }
                if (ResultCode == "D" & UserRemarks.Length == 0)
                {
                    Errors.Add("Disapprovals must have remarks included in order to be saved.");
                    return(false);
                }
                return(true);

            case "C":
                if (User.current_access == UserAccess.access_type.public_access ||
                    User.current_access == UserAccess.access_type.basic_access ||
                    User.current_access == UserAccess.access_type.inspector_access ||
                    User.current_access == UserAccess.access_type.contract_access)
                {
                    if (ResultADC.Length != 0 && InspDateTime.ToLocalTime() < DateTime.Today.AddDays(-2))
                    {
                        Errors.Add("Cannot cancel a completed inspection.  This inspection was completed on: " + InspDateTime.ToShortDateString());
                        return(false);
                    }
                    if (UserRemarks.Trim().Length == 0 && User.current_access != UserAccess.access_type.public_access)
                    {
                        Errors.Add("You must include a reason why this inspection is being canceled in the Remarks field.");
                        return(false);
                    }
                    return(true);
                }
                else
                {
                    Errors.Add("Unauthorized Access.");
                    return(false);
                }

            default:
                Errors.Add("Unauthorized Access.");
                return(false);
            }
        }
        private static bool UpdateStatus(int InspectionId,
                                         string ResultCode,
                                         string OldResult,
                                         string Remarks,
                                         string Comments,
                                         int PrivateProviderInspectionId,
                                         UserAccess User,
                                         string PermitNumber = "",
                                         string HoldInput    = "")
        {
            var dp = new DynamicParameters();

            dp.Add("@InspectionId", InspectionId);
            dp.Add("@Remarks", Remarks);
            dp.Add("@ResultCode", ResultCode);
            dp.Add("@Poster", User.user_name);
            dp.Add("@User", User.display_name);
            if (ResultCode != OldResult)
            {
                dp.Add("@FirstComment", $"Status changed from {GetResultDescription(OldResult)} to {GetResultDescription(ResultCode)}.");
                dp.Add("@SecondComment", Comments);
            }
            else
            {
                dp.Add("@FirstComment", Comments);
                dp.Add("@SecondComment", "");
            }

            string sql = $@"
        USE WATSC;

        UPDATE bpINS_Request
        SET 
          ResultADC = CASE WHEN @ResultCode = '' THEN NULL
                           WHEN @ResultCode IN ('A','D','P','N','C') THEN @ResultCode END,
          InspDateTime = CASE WHEN @ResultCode = '' THEN NULL
                              WHEN @ResultCode IN ('A','D','P','N','C') THEN GETDATE() END,
          Remarks = @Remarks,
          Poster = @Poster,
          ChrgCode = @ChargeCode
        WHERE
          InspReqId=@InspectionId
          
          EXEC add_inspection_comment @User, @InspectionId, @FirstComment, @SecondComment
          
      ";

            if (PrivateProviderInspectionId > 0)
            {
                sql += GetPrivateProviderQuery();
                dp.Add("@PrivateProviderInspectionId", PrivateProviderInspectionId);
            }

            if (ResultCode == "D")
            {
                dp.Add("@ChargeCode", "T");
                sql += GetDenialQueries();
                dp.Add("@Amount", 35);
                dp.Add("@HoldInput", HoldInput);
                dp.Add("@PermitNumber", PermitNumber);
                dp.Add("@PermitType", GetPermitType(PermitNumber));
            }
            else
            {
                sql += GetNotDeniedQueries();
                dp.Add("@ChargeCode", null);
            }

            int i = Constants.Exec_Query(sql, dp);

            return(i > 0);
        }
        public static Inspection UpdateInspectionResult(
            string PermitNumber,
            int InspectionId,
            string ResultCode,
            string Remarks,
            string Comments,
            UserAccess User)
        {
            PermitNumber = PermitNumber.Trim();
            ResultCode   = ResultCode.Trim();
            Remarks      = Remarks.Trim();
            Comments     = Comments.Trim();
            try
            {
                Inspection current = Get(InspectionId);
                if (current == null)
                {
                    return(null);
                }

                if (current.Validate(PermitNumber, current, ResultCode, Remarks, User))
                {
                    // let's do some saving
                    switch (ResultCode)
                    {
                    case "A":
                    case "P":
                    case "N":
                    case "C":
                    case "":
                        if (current.ResultADC == "D")
                        {
                            if (IsREIPaid(current.InspReqID))
                            {
                                current.UpdateError = ("The REI has already been paid, you cannot change the result of this inspection.");
                                break;
                            }
                        }

                        if (!UpdateStatus(InspectionId, ResultCode, current.ResultADC, Remarks, Comments, current.PrivateProviderInspectionRequestId, User))
                        {
                            current.UpdateError = ("Error saving your changes, please try again. If this message recurs, please contact the helpdesk.");
                        }
                        break;


                    case "D":
                        string HoldInput = current.PermitNo + " " + current.InspectionCode + " $35";
                        if (!UpdateStatus(InspectionId, ResultCode, current.ResultADC, Remarks, Comments, current.PrivateProviderInspectionRequestId, User, PermitNumber, HoldInput))
                        {
                            current.UpdateError = ("Error saving your changes, please try again. If this message recurs, please contact the helpdesk.");
                        }
                        break;
                    }
                }

                Inspection i = Get(InspectionId);
                return(i);
            }
            catch (Exception ex)
            {
                Constants.Log(ex, "");
                return(null);
            }
        }