# encoding: utf-8
require 'fedux_org_stdlib/models/base_model'

module FeduxOrgStdlib
  module Models
    # model for import action
    module FilesystemBasedModel

      def self.included(base)
        base.extend ClassMethods
      end

      module ClassMethods

        #initialize model
        def init
          load_from_filesystem
        end

        private

        def module_name
          name = fqcn
          name.pop

          name.join('::')
        end

        def fqcn
          self.to_s.split(/::/)
        end

        def model_name
          fqcn.last
        end

        def library_name
          fqcn.first
        end

        def suffix
          raise FeduxOrgStdlib::Models::Exceptions::MethodNeedsToBeImplemented, "Please defined the method \"suffix\" to make the library work."
        end

        def model_path
          raise FeduxOrgStdlib::Models::Exceptions::MethodNeedsToBeImplemented, "Please defined the method \"model_path\" to make the library work."
        end

        def ignore
          'BORING_STRING_WHICH_SHOULD_NEVER_MATCH'
        end

        def find_files
          files = []
          Find.find(path_to_instances) do |path|
            next unless File.file? path
            next if suffix and path !~/#{suffix}$/
            next if path =~ /^\.\.?/
            next if path =~ %r{#{ignore}}

            files << path
          end

          files
        rescue
          raise FeduxOrgStdlib::Models::Exceptions::NoImplementationsForModelFound, "You might need to create the directory\"#{File.dirname(path_to_instances)}\"."
        end

        def path_to_instances
          return_path = ::File.expand_path("../../#{model_name.pluralize.underscore}", model_path )

          FeduxOrgStdlib.logger.debug(self) { "Path to instances of model: #{return_path}" }

          return_path
        end

        def name(path)
          name = File.basename(path, suffix ).to_sym
          raise FeduxOrgStdlib::Models::Exceptions::UnauthorizedUseOfKeyword if forbidden_keywords.include? name

          FeduxOrgStdlib.logger.debug(self) { "Name of model: #{name}" }

          name
        end

        def load_from_filesystem
          raise FeduxOrgStdlib::Models::Exceptions::MethodNeedsToBeImplemented
        end

        def forbidden_keywords
          [ ]
        end

      end

    end
  end
end