#The MIT License (MIT)
#
#Copyright (c) 2016 - 2026 rick barrette
#
#Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
#
#The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
#
#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

module RedmineQbo
  module Hooks
    class IssuesHookListener < Redmine::Hook::ViewListener

      include IssuesHelper

      # Edit Issue Form
      # Here we build the required form components before passing them to a partial view formatting. 
      def view_issues_form_details_bottom(context={})
        log "view_issues_form_details_bottom: Building form components for quickbooks customer, estimate, and invoice data"
        f = context[:form]
        issue = context[:issue]
        project = context[:project]

        # Customer Name Text Box with database backed autocomplete
        # onchange event will update the hidden customer_id field        
        search_customer = f.text_field :customer,
          class: "customer-name",
          autocomplete: "off",
          data: {
            autocomplete_url: "/customers/autocomplete"
          }

        # We need to handle 3 cases for the onchange event of the customer name field:
        # 1. New issue Withough project:  /issues/new.js
        # 2. New issue With project:      /projects/rmt/issues/new.js
        # 3. Existing issue:              /issues/<ID>/edit.js
        # The built in helper update_issue_form_path requires a project object to determine the correct path for new vs existing issues, 
        # but it doesn't work for issue.project when creating new issues not in a project i.e. http://redmine.domain.com/issues/new . 
        # So we need to figure out how to get a the @project from the controller calling the hook.
        #
        # If this is not handled correctly, it leads to a 422 error when creating a new issue and selecting a customer.
        js_path = "updateIssueFrom('#{escape_javascript update_issue_form_path(project, issue)}', this)"
        log js_path

        # This hidden field is used for the customer ID for the issue
        # the onchange event will reload the issue form via ajax to update the available estimates
        customer_id = f.hidden_field :customer_id,
          id: "customer_id",
          onchange: js_path.html_safe

        # Generate the drop down list of quickbooks estimates owned by the selected customer
        select_estimate = f.select :estimate_id, 
          issue.customer ? issue.customer.estimates.pluck(:doc_number, :id).sort! {|x, y| y <=> x} : [], 
          selected: issue.estimate ? issue.estimate.id : nil, 
          include_blank: true
        
        # Pass all prebuilt form components to our partial
        context[:controller].send(:render_to_string, {
          partial: 'issues/form_hook',
            locals: {
              search_customer: search_customer, 
              customer_id: customer_id, 
              select_estimate: select_estimate
            } 
          }
        )
      end

      # View Issue
      # Displays the quickbooks customer, estimate, & invoices attached to the issue
      def view_issues_show_details_bottom(context={})
        issue = context[:issue]
        
        # Build a list of invoice links
        invoice_link = ""
        if issue.invoices
          issue.invoices.each do |i|
            invoice_link += "#{link_to i, i, target: :_blank}<br/>"
          end
        end
        
        context[:controller].send(:render_to_string, {
          partial: 'issues/show_details',
            locals: {
              customer: issue.customer ? link_to(issue.customer) : nil, 
              estimate_link: issue.estimate ? link_to(issue.estimate, issue.estimate, target: :_blank) : nil, 
              invoice_link: invoice_link.html_safe,
              issue: issue
            } 
          })
      end

      private

      def log(msg)
        Rails.logger.info "[IssuesHookListener] #{msg}"
      end
      
    end
  end 
end