class MailType < ApplicationRecord
  has_many :mail_contents, :dependent => :destroy
  belongs_to :mail_type_reference, :class_name => "MailType"

  has_many :mail_hists, :dependent => :destroy
  
  accepts_nested_attributes_for :mail_contents

  belongs_to :mail_type_cat
  
  belongs_to :circuit

  acts_as_sorting :fields => {
    :default_title => {:name => "Sujet", :reorder => true},
    :default_message => {:name => "Contenu", :reorder => true},
    
    :actions => "Actions",
  }
 

  def self.find_or_create(slug)
    if mail_type = self.where(:slug => slug).first
      return mail_type
    else
      mail_type = MailType.create(:slug => slug)
      LangSite.all.each do |ls|
        mail_type.mail_contents.create(:lang_site => ls, :enabled => true, :content_type => "text")
      end
      return mail_type

    end
  end


  def lang(slug)
    self.mail_contents.where(:lang_site => LangSite.where(:slug => slug.to_s).first).first
    
    
  end
  
  def default_title
    self.lang(:fr).subject if self.lang(:fr)
  end
  
  def default_message
    self.lang(:fr).message.to_s.truncate(100) if self.lang(:fr)
  end

end
