module EasyProjectCom
  module EasyPatch
    module AccountControllerPatch

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

          alias_method_chain :account_locked, :easy_project_com
          alias_method_chain :autologin, :easy_project_com

        end
      end

      module InstanceMethods

        def account_locked_with_easy_project_com(user, redirect_path=signin_path)
          if User.active.count >= EasyLicenseManager.get_internal_user_limit
            owner = User.owner
            mail = owner ? owner.mail : 'support@easyproject.com'
            flash[:error] = l(:'easy_trial_expiration.text_your_account_has_been_locked') + '<br />' + l(:'easy_trial_expiration.text_contact_admin', mail: view_context.mail_to(mail)).html_safe
            redirect_to redirect_path
          else
            account_locked_without_easy_project_com(user, redirect_path)
          end
        end

        def autologin_with_easy_project_com
          if (key = api_key_from_request)
            if (user = User.find_by_api_key(key))
              if user.easy_show_invitation? && (access_token = params.delete(:access_token)).present?
                uri = URI.parse OmniAuth::Strategies::Sso.default_options['client_options'].try(:[], 'site')
                uri.path = '/auth/sso/user.json' # by_mail or token provided by Joomla
                uri.query = 'oauth_token=' + access_token
                begin
                  json = JSON.load uri
                  if (info = json['info'])
                    user.update_columns({
                                               # must_change_passwd: false,
                                               sso_provider: json['provider'],
                                               sso_uuid: json['id'],
                                               firstname: info['first_name'],
                                               lastname: info['last_name'],
                                               easy_avatar_url: info['image']
                                           })
                  end
                rescue OpenURI::HTTPError => e
                  #
                end
              end
            elsif key == EasyDemoUser.auth_key
              user = EasyDemoUser.first || User.active.where(admin: true).first
            end

            if user
              self.logged_user = user
              set_autologin_cookie(user)
              return redirect_back_or_default(home_url)
            end
          end

          redirect_to signin_path(back_url: params[:back_url])
        end

      end

    end
  end
end
EasyExtensions::PatchManager.register_controller_patch 'AccountController', 'EasyProjectCom::EasyPatch::AccountControllerPatch'
