# frozen_string_literal: true

module MetaAttribute
  extend ActiveSupport::Concern

  included do
    def sections
      self.class.sections
    end
  end

  class_methods do
    def sections
      @sections
    end

    def section(name)
      raise "Required meta_attribute invoke in block!" unless block_given?
      @section = name
      yield
      @section = nil
    end

    def fields(section:)
      @fields[section]
    end

    def meta_attribute(key, options = {})
      options[:form_ctrl] ||= "text"
      @sections ||= []
      @fields ||= {}
      key = key.to_s
      raise "key invalid" if key.blank?

      section_scope = @section
      if key.include?(".")
        section_arg = key.split(".", 2).first
        raise "key section invalid" if section_arg.blank?
      end
      if section_scope
        s = section_arg.nil? ? section_scope : "#{section_scope}.#{section_arg}"
        @sections << s if !@sections.include?(s)
        @fields[section_scope] ||= []
        @fields[section_scope] << {key: key}.merge(options)
      elsif !section_arg.nil?
        @sections << section_arg if !@sections.include?(section_arg)
      end

      define_method("#{key}=") do |value|
        puts "pressss:#{preferences.class}"
        if options[:type] == :bool
          value = value == "true"
        end
        self.preferences = if !preferences.is_a?(Hash)
          {key.to_sym => {value: value}}
        else
          (preferences || {}).merge({key.to_sym => {value: value}})
        end
      end

      define_method(key) do
        return nil if preferences.blank? || preferences[key].blank?
        preferences[key]["value"]
      end
    end
  end
end
