module EasyProjectCom
  module EasyPatch
    module ProjectsControllerPatch

      def self.included(base)
        base.send(:include, InstanceMethods)
        base.class_eval do

          skip_before_action :render_403
          before_action :render_limit_reached, only: [:new, :create, :unarchive, :bulk_unarchive], if: ->{!EasyLicenseManager.has_license_limit?(:active_project_limit)}

          alias_method_chain :new, :easy_project_com

          def render_limit_reached
            render(template: 'easy_trial_expiration/limit_reached', status: 402)
            false
          end

        end
      end

      module InstanceMethods

        def new_with_easy_project_com
          if params['tab'] == 'project_from_template'
            retrieve_query(EasyProjectTemplateQuery)
            sort_init(@query.sort_criteria_init)
            sort_update(@query.sortable_columns)
            prepare_easy_query_render
          end

          if request.xhr?
            if @entities
              respond_to do |format|
                format.html { render_easy_query }
              end
            else
              render_404
              return false
            end
          else
            new_without_easy_project_com
          end
        end

      end

    end
  end
end
EasyExtensions::PatchManager.register_controller_patch 'ProjectsController', 'EasyProjectCom::EasyPatch::ProjectsControllerPatch'
