module Workarea
  module MagentoMigrator
    class CatalogCategory < MagentoBase

      class << self
        def ids_to_include
          "SELECT distinct(category_id) FROM catalog_category_product "
        end

        def table_name
          @@table_name ||= 'catalog_category'
        end

        def select_content_pages_query
          select_query = "SELECT #{select_columns} FROM #{table_name}_entity e #{join_clause} "
          select_query += "\nwhere e.entity_id not in (#{ids_to_include}) and e.parent_id>1 and e.level >1"
        end

        def catalog_category_menu
          client.query(select_content_pages_query).to_a
        end

        def import_content_pages
          File.open("#{Rails.root.to_s}/data/content_pages.json", "w"){ |f|
            f.write(JSON.pretty_generate(catalog_category_menu))
          }
        end

        def import_catagories
          File.open("#{Rails.root.to_s}/data/categories.json", "w"){ |f|
            f.write(JSON.pretty_generate(categories.to_a))
          }
          File.open("#{Rails.root.to_s}/data/soft_categories.json", "w"){ |f|
            f.write(JSON.pretty_generate(soft_categories.to_a))
          }
        end

        def categories_content
          {home_categories: 9, business_categories: 10, shop_murals_categories: 8}.each do |category_name, id|
            categories = client.query(content_categories_query(id)).to_a
            categories_content = categories.map { |cat|
              {
                name: cat['name'],
                slug: cat['url_key'],
                h1_tag: cat['h1_tag'],
                bottom_content: (cat['bottom_content'] || ''),
                description: (cat['description'] || '')
              }
            }
            File.open("#{Rails.root.to_s}/data/#{category_name}.json", "w"){ |f|
              f.write(JSON.pretty_generate(categories_content))
            }
          end
        end

        def content_categories_query(parent_id)
          "SELECT #{select_columns} FROM #{table_name}_entity e #{join_clause} where e.parent_id=#{parent_id} and v19.value=1 order by e.position asc"
        end


        def categories
          client.query(categories_query).to_a
        end

        def soft_categories
          client.query(soft_categories_query).to_a
        end

        def soft_categories_query
         " #{select_query} and e.children_count > 0 order by e.parent_id asc "
       end

       def categories_query
        " #{select_query}  and e.children_count = 0 order by e.parent_id asc "
      end

      end # class self declaration

    end # class end
  end
end