module EasyProjectCom
  module EasyPatch
    module ApplicationHelperPatch

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

          alias_method_chain :project_header_breadcrump, :easy_project_com
          alias_method_chain :new_project_button, :easy_project_com

          def inline_manual_topics
            if (key = EasyHostingServices::EasyCloud.config.inline_manual_key).present?
              begin
              if (response = EasyUtils::HttpUtils.get_request_body('https://inlinemanual.com/', "/api/player/topics?site_key=#{key}"))
                return JSON.parse(response)
              end
              rescue StandardError
                Rails.logger.error('InlineManual topics request failed')
              end
            end

            return []
          end

          def easy_new_entity_time_entry_path(project = nil)
            issue = @issue.try(:persisted?) && @issue

            project ||= (@issue.try(:project_id) || @project)
            project = (project.try(:persisted?) && project)

            new_easy_project_com_time_entry_path(project, issue)
          end

          def ep_com_easy_issue_timer_button(issue, user=User.current)
            return unless EasyIssueTimer.active?(issue.project) && User.current.allowed_to?(:log_time, issue.project) && issue.editable?
            timer = issue.easy_issue_timers.where(user_id: user.id).running.last
            if timer && !timer.paused?
              links = ''
              links << link_to(l(:button_easy_issue_timer_stop), easy_issue_timer_stop_path(issue, timer_id: timer), class: 'button-positive button-outlined icon icon-checked-circle', method: :post, title: l(:title_easy_issue_timer_button_stop), onclick: "$(this).css({'z-index': -1})")
              links << link_to(l(:button_easy_issue_timer_pause), easy_issue_timer_pause_path(issue, timer_id: timer), class: 'button-negative button-outlined icon icon-pause', method: :post, title: l(:title_easy_issue_timer_button_pause), onclick: "$(this).css({'z-index': -1})")
              links.html_safe
            else
              links = ''
              links << link_to(l((timer.nil? ? :button_easy_issue_timer_play : :button_easy_issue_timer_resume)), easy_issue_timer_play_path(issue, timer_id: timer), class: 'button-positive button-outlined icon icon-play', method: :post, title: l(:title_easy_issue_timer_button_play), onclick: "$(this).css({'z-index': -1})")
              links.html_safe
            end
          end

          def personalize_greeting(user, entity, action = 'new')
            options = {author: entity.author, entity: l('mail_label_' + entity.class.name.underscore)}
            if user && user == entity.assigned_to
              l('mail_greeting_' + action + '_my', options.merge(user: user.firstname))
            elsif user
              l('mail_greeting_' + action, options.merge(user: user.firstname))
            else
              l(:mail_without_greeting)
            end
          end

        end
      end

      module InstanceMethods

        def project_header_breadcrump_with_easy_project_com(entity, options={})
          project = entity.project if entity.respond_to?(:project)
          project ||= @project
          breadcrump = Array.new
          breadcrump << link_to(l(:label_templates_plural), templates_path) if project.easy_is_easy_template
          project.self_and_ancestors.each do |p|
            project_name = h(p.name)
            project_name << " <span class=\"menu-project-template\">#{l(:label_menu_project_template)}</span>".html_safe if p.easy_is_easy_template?
            project_name << " <span class=\"menu-project-template\">#{l(:field_is_planned)}</span>".html_safe if p.is_planned
            if project.id == p.id
              current_project = link_to(project_name, url_to_project(p))
              if User.current.favorite_projects.where(:id => project.id).exists?
                fav_css = 'icon-fav favorited'
                title = l(:label_unfavorite)
              else
                fav_css = 'icon-fav-off'
                title = l(:label_favorite)
              end
              current_project << link_to('', favorite_project_path(p), :method => :post, :remote => true, :class => "icon #{fav_css}", :id => "favorite_project_#{p.id}", :title => title)
              breadcrump << content_tag(:span, current_project, :class => 'self')
            else
              breadcrump << link_to_if(p.visible?, project_name, url_to_project(p), {:class => 'ancestor'}) unless in_mobile_view?
            end
          end

          if options[:link_tail]
            link_to_tail = link_to_entity(entity, options)
            breadcrump << truncate_html(link_to_tail, 60) if entity && !entity.new_record? && !in_mobile_view?
          end

          return breadcrump.join('<span class="separator"> &#187; </span>').html_safe
        end

        def new_project_button_with_easy_project_com(*args)
          if !EasyLicenseManager.has_license_limit?(:active_project_limit)
            link_to(l(:label_project_new), easy_trial_expiration_limit_reached_path, class: 'button-positive icon icon-add', remote: true)
          else
            new_project_button_without_easy_project_com(*args)
          end
        end

      end

    end
  end
end
EasyExtensions::PatchManager.register_helper_patch 'ApplicationHelper', 'EasyProjectCom::EasyPatch::ApplicationHelperPatch'
