module EasyProjectCom
  module EasyPatch
    module EasyCalendarMailerPatch

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

          alias_method_chain :easy_meeting_invitation, :easy_project_com

          def invitation_subject(meeting)
            l(:title_meeting_invitation, name: meeting.name)
          end

        end
      end

      module InstanceMethods

        def easy_meeting_invitation_with_easy_project_com(easy_meeting, mail, invitee_mails=[], options={})
          meeting_url = easy_meeting_url(easy_meeting)
          invitee_mails = [mail] unless invitee_mails.present?

          ical = Icalendar::Calendar.new
          ical.event do |e|
            e.uid          = easy_meeting.uid
            e.url          = meeting_url unless options[:external]
            e.summary      = easy_meeting.name
            e.location     = easy_meeting.easy_room.to_s if easy_meeting.easy_room
            e.dtstart      = easy_meeting.start_time.utc.iso8601(0).gsub(/[-:]/, '')
            e.dtend        = easy_meeting.end_time.utc.iso8601(0).gsub(/[-:]/, '')
            e.organizer = "mailto:#{easy_meeting.author.mail}" if easy_meeting.author.mail.present?
            Array(invitee_mails).each do |mail|
              e.append_attendee "mailto:#{mail}"
            end
          end

          @easy_meeting = easy_meeting

          if (@invited_user = User.find_by_mail(mail))
            set_language_if_valid(@invited_user.language)
          end

          @user = @invited_user || User.current
          @invitor = User.current.logged? ? User.current : easy_meeting.author
          @external = options[:external]

          mixed = mail(to: mail, subject: invitation_subject(@easy_meeting)) do |format|
            format.html
            format.text
            format.ics {render text: ical.to_ical
            }
          end
          mixed.content_type 'multipart/mixed'
          mixed.header['content-type'].parameters[:boundary] = mixed.body.boundary

          alt = Mail::Part.new {content_type 'multipart/alternative'}
          mixed.parts.delete_if {|p| alt.add_part p}
          alt.parts[2].content_type 'text/calendar; charset=UTF-8; method=REQUEST'

          mixed.attachments['invitation.ics'] = {content: ical.to_ical, content_type: 'application/ical'}
          mixed.add_part(alt)
          mixed.body.set_sort_order(['multipart/alternative', 'application/ical'])
        end

      end
    end
  end
end
EasyExtensions::PatchManager.register_model_patch 'EasyCalendarMailer', 'EasyProjectCom::EasyPatch::EasyCalendarMailerPatch'
