module EasyXmlData
  class EasyPageTemplateExporter < Exporter
    require 'zip'

    def initialize(page_template_id)
      @page_template_id = page_template_id

      collect_entities
    end

    def self.exportables
      @exportables ||= []
    end

    def self.exportable_labels
      @exportable_labels ||= Hash.new
    end

    def build_xml(bob)
      bob.easy_xml_data do
        @page_templates.to_xml(builder: bob, skip_instruct: true, except: [
            :easy_pages_id,
            :is_default,
            :position
        ], procs: [
            Proc.new{|options, record| options[:builder].tag!('easy-page', record.page_definition.page_name)},
        ])
        @easy_page_template_tabs.to_xml(builder: bob, skip_instruct:true, except:[
            :entity_id
        ])
        @easy_page_template_modules.sort_by { |epm| epm.position }.to_xml(builder: bob, skip_instruct: true, except: [
            :uuid,
            :easy_page_templates_id,
            :easy_page_available_zones_id,
            :easy_page_available_modules_id,
            :position,
            :settings
        ], procs: [
            Proc.new{|options, record| options[:builder].tag!('id', record.id)},
            Proc.new{|options, record| options[:builder].tag!('easy-page-template', record.easy_page_templates_id)},
            Proc.new{|options, record| options[:builder].tag!('easy-page-zone', record.zone_definition.zone_name)},
            Proc.new{|options, record| options[:builder].tag!('easy-page-module', record.module_definition.type)},
            Proc.new{|options, record| options[:builder].tag!('settings', record.settings.to_yaml, :type => 'yaml')}
        ]) unless @easy_page_template_modules.blank?
      end
    end

    private

    def collect_entities
      @attachment_files = []

      @page_templates = EasyPageTemplate.where(id: @page_template_id)
      @easy_page_template_tabs = EasyPageTemplateTab.where(page_template_id: @page_template_id)
      @easy_page_template_modules = EasyPageTemplateModule.where(easy_page_templates_id: @page_template_id);
    end

  end
end
