module M2yBiz
  module Wallet
    class Cards < Base

      def initialize(token)
        @headers = json_headers(true, token)
      end

      def listCards(wallet = nil, holder = nil)
        if wallet.blank?
          # https://code.biz.com.br/api-details#api=wallet-lancamentos&operation=get-cards
          url = "#{base_url}#{Constants::Paths::HOLDER_CARDS_PATH}"
          url = url + "&holderId=#{holder}" unless holder.blank?
        else
          # https://code.biz.com.br/api-details#api=wallet-lancamentos&operation=get-wallets-walletid-cards
          url = "#{base_url}#{Constants::Paths::WALLET_CARDS_PATH}".gsub(':wallet', wallet)
        end
        request = HTTParty.get(url, headers: @headers)
        BizHelper.parse_response(request)
      end

      def unlockCard(wallet, card, deliveryNumber = nil)
        # https://code.biz.com.br/api-details#api=wallet-lancamentos&operation=post-wallets-walletid-cards-cardid-unblock
        return Base::FAILURE if wallet.blank? || card.blank?
        url = "#{base_url}#{Constants::Paths::UNBLOCK_CARD_PATH}".gsub(':wallet', wallet).gsub(':card', card)
        body = deliveryNumber.present? ? { "deliveryNumber": deliveryNumber } : {}
        request = HTTParty.post(url, body: body.to_json, headers: @headers)
        BizHelper.parse_response(request)
      end

      def blockCard(wallet, card)
        # https://code.biz.com.br/api-details#api=wallet-lancamentos&operation=post-wallets-walletid-cards-cardid-block
        return Base::FAILURE if wallet.blank? || card.blank?
        url = "#{base_url}#{Constants::Paths::UNBLOCK_CARD_PATH}".gsub(':wallet', wallet).gsub(':card', card).gsub('unblock', 'block')
        request = HTTParty.post(url, headers: @headers)
        BizHelper.parse_response(request)
      end

      def updateCardPass(card, newPassword)
        # https://code.biz.com.br/api-details#api=wallet-lancamentos&operation=post-cards-cardid-change-password
        return Base::FAILURE if card.blank? || newPassword.blank?
        url = "#{base_url}#{Constants::Paths::UPDATE_CARD_PASS_PATH}".gsub(':card', card)
        body = { "password": encrypt(newPassword) }.to_json
        request = HTTParty.post(url, body: body, headers: @headers)
        BizHelper.parse_response(request)
      end

    end
  end
end
