module PaymentGateways
  class PaymentExpressCrypt

    # builds an auth url
    #
    # first an auth xml is builded, example:
    # <GenerateRequest>
    #   <PxPayUserId>DPSDemo4_Dev</PxPayUserId>
    #   <PxPayKey>************************</PxPayKey>
    #   <AmountInput>173.45</AmountInput>
    #   <CurrencyInput>EUR</CurrencyInput>
    #   <MerchantReference>yklgm1ujpkuyutjogswfv145</MerchantReference>
    #   <TxnType>Purchase</TxnType>
    #   <UrlFail>https://www.dpsdemo.com/PxPaySuccess.aspx</UrlFail>
    #   <UrlSuccess>https://www.dpsdemo.com/PxPaySuccess.aspx</UrlSuccess>
    #   <EnableAddBillCard>1</EnableAddBillCard>
    # </GenerateRequest>
    #
    # then we call their service to encrypt the request, example of what they return
    # "<Request valid=\"1\"><URI>https://sec2.paymentexpress.com/pxpay/pxpay.aspx?userid=3scale_Dev&amp;request=v5jXXmqLJuKdzXYtJjvKAKrYlZrcyus9X7qb9BNKxUh0krn4BySoS3x-PTvEskXAnrO7pHPLXKOX91-AV4_zxMMXxHIWmA01PL_AuHeoIJVZqP11ofTJM4v1XF13IJWqy7BY8c6zJvHx5mpp4F0xH8RuyPuKJjTmdIFqVOEjNVJs1kALRYAvmNquB3x7mghjeasbhBCKbxa_EoVdDkcJMxu53sXLKokadwDNGU0m3eVhOmfjVQPQcJaMv3n4w1Q43kL4EVUvwHsU9M6szDllJBhBDMQWoKI37-iXYN_F7P993NDmyXXxv_bYpEZbvevS3RNfpQO0U3avA=</URI></Request>"
    #
    # then the uri is extracted from there
    def self.auth_url(args)
      xml = "<GenerateRequest><PxPayUserId>#{args[:login]}</PxPayUserId><PxPayKey>#{args[:password]}</PxPayKey><MerchantReference>auth-#{args[:auth_text]}</MerchantReference><TxnType>Auth</TxnType><AmountInput>0.10</AmountInput><CurrencyInput>EUR</CurrencyInput><UrlSuccess>#{args[:success_url]}</UrlSuccess><UrlFail>#{args[:failure_url]}</UrlFail><EnableAddBillCard>1</EnableAddBillCard></GenerateRequest>"
      Rails.logger.debug "Payment Express auth xml #{xml}"

      crypted_request = RestClient.post "https://sec2.paymentexpress.com/pxpay/pxaccess.aspx", :request => xml
      Rails.logger.debug "Payment Express crypted auth xml #{crypted_request}"
      xml_request = Nokogiri::XML::Document.parse(crypted_request)

      xml_request.xpath(".//Request/URI").text
    end

    # decrypts payment_express result and returns the AuthCode
    #
    # this is what comes in the params from payment_express
    # result=v544vDsBacaHfaIFCafOpY-D20mHd2Gqz0ldG_LvYAfQX6O3ffKsJoTO82kjhQuTV3W5pk36HdZDz7oLbVogLKalyQowQbuxk0c-IfwNHZHWq1uu1cPEOb__ZiKxhYUow9UtcvrePa55UPw__YB-Hdb8AUvJJ3hd2jHwbX5VR7B5iIm4C2SqDeEzQJOOWhvdC4uat9gE0OiCr64MtQdhhXpOXQjlNIQT0H1KU_y_zpsCemfjVQPQcJaHK0cauv1q3KMIqfS8xP6eO3c3tBwMWImQW3OtEbASCs5P1GSvgi9V7WPsalDEt-BEPflx4JtDbOR5CA4KFZJaRuIu2MAHjSSEG5cDnrUvu94p36rf8xjqjFao8BMRAhgUJEUSHiE_VamfSF2Oq1cBAbd5tXOan08v_BkpaduUqVPn4ZlVFIMS5LL8vA7mMbF3YSDagN8DOk2DYkMFXYICeDkk9vTpY2PRtSM7rihaNpXDikgrvIB7I3tln-2Gneow==&userid=3scale_Dev
    #
    # we turn it into an xml to post to their service to decrypt it for us (ProcessResponse...)
    #
    # and this is a sample decrypted response
    # "<Response valid=\"1\"><Success>1</Success><TxnType>Auth</TxnType><CurrencyInput>EUR</CurrencyInput><MerchantReference>auth-Mobile App Developer</MerchantReference><TxnData1></TxnData1><TxnData2></TxnData2><TxnData3></TxnData3><AuthCode>225148</AuthCode><CardName>MasterCard</CardName><CardHolderName>DONNIE YEN</CardHolderName><CardNumber>543111........11</CardNumber><DateExpiry>1212</DateExpiry><ClientInfo>85.50.90.46</ClientInfo><TxnId>P04C2AC3C6342078</TxnId><EmailAddress></EmailAddress><DpsTxnRef>00000008004149d3</DpsTxnRef><BillingId></BillingId><DpsBillingId></DpsBillingId><AmountSettlement>1.00</AmountSettlement><CurrencySettlement>EUR</CurrencySettlement><DateSettlement>20110503</DateSettlement><TxnMac>46DD54E8</TxnMac><ResponseText>APPROVED</ResponseText><CardNumber2></CardNumber2><IssuerCountryId>840</IssuerCountryId></Response>"
    def self.auth_response(args)
      xml = "<ProcessResponse><PxPayUserId>#{args[:login]}</PxPayUserId><PxPayKey>#{args[:password]}</PxPayKey><Response>#{args[:result]}</Response></ProcessResponse>"
      Rails.logger.info "[Payment gateway] Payment Express process response of auth xml #{xml}"

      decrypted_response = RestClient.post("https://sec2.paymentexpress.com/pxpay/pxaccess.aspx",
                                            :request => xml)
      Rails.logger.info "[Payment gateway] Payment Express decrypted response of auth xml #{decrypted_response}"
      xml_response = Nokogiri::XML::Document.parse(decrypted_response)

      if xml_response.xpath(".//Response/Success").text == "1"
        {
          :auth_code   => xml_response.xpath(".//Response/DpsBillingId").text, # xml_response.xpath(".//Response/AuthCode").text,
          :card_number => xml_response.xpath(".//Response/CardNumber").text,
          :expiry_date => xml_response.xpath(".//Response/DateExpiry").text
        }
      end
    end

  end
end
