# 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 ContentFrame < ApplicationRecord
  # attr_accessible :title, :body
  
  # タイトル
  validates :title, presence: true
  validates :title, allow_blank: true, 
    length: { maximum: 18 }
  
  # 説明
#  validates :description, presence: true
#  validates :description, allow_blank: true, 
#    length: { maximum: 270 }
  validate :validate_description

  # 説明検証（return_flag=true の場合はメッセージも返す）
  def validate_description(return_flag = false)
    return if self.description.blank?

    result = ''

    description = self.description.to_s

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

    len = text_length + break_length

    limit = 270

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

    return result if return_flag
  end
end
