# frozen_string_literal: true

# -*- coding: utf-8 -*-
# Copyright (C) 2010 NMT Co.,Ltd.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>

class SendModerater < ApplicationRecord
  # attr_accessible :title, :body
  belongs_to :send_moderate
  belongs_to :moderater
  belongs_to :user
  
  # 送信却下理由
#  validates :content, presence: true
#  validates :content, allow_blank: true,
#    length: { maximum: 3000 }
  validate :validate_content

  # 送信却下理由検証（return_flag=true の場合はメッセージも返す）
  def validate_content(return_flag = false)
    return if self.content.blank?

    result = ''

    content = self.content.to_s

    # 改行以外の文字数 （「\r\n」以外の文字数をcountメソッドで数える）
    text_length = content&.count("^\r\n") || 0
    # 改行の回数 （「\r\n」という塊の数だけscanメソッドで配列にし、その長さをlengthメソッドで求めている）
    break_length = content&.scan("\r\n")&.length || 0

    len = text_length + break_length

    limit = 3000

    if len > limit
      # 送信却下理由の文字数が不正です
      errors.add(:message, "は#{limit}文字以下にしてください")
      result = "送信却下理由は#{limit}文字以下にしてください"
    end

    return result if return_flag
  end
end
