class EasyPrintableTemplate < ActiveRecord::Base
  include Redmine::SafeAttributes

  PAGES_ORIENTATION_PORTRAIT = 'portrait'
  PAGES_ORIENTATION_LANDSCAPE = 'landscape'

  belongs_to :project
  belongs_to :author, :class_name => 'User', :foreign_key => 'author_id'
  has_many :easy_printable_template_pages, :dependent => :destroy

  validates :name, :author, :presence => true

  attr_protected :id

  after_initialize :set_default_values, :if => Proc.new { |template| template.new_record? }

  accepts_nested_attributes_for :easy_printable_template_pages, :allow_destroy => true

  safe_attributes 'name', 'pages_orientation', 'pages_size', 'private', 'author_id',
    'category', 'easy_printable_template_pages_attributes', 'description'

  def self.create_from_view!(attrs, options = {})
    plugin_name = options[:plugin_name] || 'easy_extensions'
    internal_name = options[:internal_name]
    template_name = options[:template_name] || plugin_name
    template_path = options[:template_path] || File.join(EasyExtensions::RELATIVE_EASYPROJECT_EASY_PLUGINS_PATH, plugin_name, 'app', 'views', 'easy_printable_templates', "#{internal_name || template_name}.html")

    return nil unless File.exists?(template_path)

    if internal_name
      template = EasyPrintableTemplate.find_or_initialize_by(:internal_name => internal_name)
    else
      template = EasyPrintableTemplate.find_or_initialize_by(:name => attrs[:name] || template_name)
    end

    template.safe_attributes = attrs

    template.easy_printable_template_pages.clear if !template.new_record?
    template.easy_printable_template_pages.build(:page_text => File.read(template_path))
    template.set_default_values
    template.save!
    template
  end

  def dup_with_pages
    clone = self.dup
    self.easy_printable_template_pages.each do |page|
      clone.easy_printable_template_pages << page.dup
    end
    clone.author = User.current
    clone.internal_name = nil
    clone
  end

  def self.translate_pages_orientation(orientation)
    l(orientation, :scope => [:easy_printable_template, :pages_orientation])
  end

  def self.find_internal_name(internal_name)
    EasyPrintableTemplate.where(:internal_name => internal_name).first
  end

  def translate_pages_orientation
    self.class.translate_pages_orientation(self.pages_orientation)
  end

  def editable?
    self.internal_name.blank?
  end

  def deletable?
    self.internal_name.blank?
  end

  def category_caption
    EasyPrintableTemplate.category_caption(category)
  end

  def self.category_caption(category)
    l(category, :scope => [:easy_printable_templates_categories], :default => category.humanize)
  end

  def set_default_values
    self.pages_orientation ||= EasyPrintableTemplate::PAGES_ORIENTATION_PORTRAIT
    self.pages_size ||= 'a4'
    self.author ||= User.current
  end

end
