module EasyXmlData
  class EasyPageExporter < Exporter
    require 'zip'

    def initialize(page_id)
      @page_id = page_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
        @pages.to_xml(builder: bob, skip_instruct: true, except: [
            :easy_pages_id,
            :easy_page_available_zones_id,
            :easy_page_available_modules_id,
            :settings
        ])
        @easy_page_user_tabs.to_xml(builder: bob, skip_instruct:true, except:[
            :entity_id
        ])
        @easy_page_zone_modules.sort_by { |epm| epm.position }.to_xml(builder: bob, skip_instruct: true, except: [
            :uuid,
            :easy_pages_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', record.easy_pages_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_zone_modules.blank?
      end
    end

    private

    def collect_entities
      @attachment_files = []

      @pages = EasyPage.where(id: @page_id)
      @easy_page_user_tabs = EasyPageUserTab.where(page_id: @page_id)
      @easy_page_zone_modules = EasyPageZoneModule.where(easy_pages_id: @page_id)
    end

  end
end
