class OpenWifi::SecurityService < OpenWifi::BaseApi
  API_ENDPOINT = get_API_url_endpoint APPLICATION['defaults']['OPEN_WIFI']['SECURITY']['HOSTNAME'], APPLICATION['defaults']['OPEN_WIFI']['SECURITY']['PORTNUMBER']
  
  def initialize(int_type=nil)
    @int_type = int_type
  end

  def oauth2
    end_point = get_controller_details @int_type, 'SECURITY'
    if @int_type.present?
      res = WrapperApi.send_oauth_request 'POST', (end_point + 'oauth2'), {"userId" => (@int_type.try(:details) || {})['sdk_user'], "password" => (@int_type.try(:details) || {})['sdk_password']}
    else
      res = WrapperApi.send_oauth_request 'POST', (end_point + 'oauth2'), {"userId" => APPLICATION['defaults']['OPEN_WIFI']['SDK_USER'], "password" => APPLICATION['defaults']['OPEN_WIFI']['SDK_PASSWORD']}
    end
    if res.present?
      if res['ErrorCode'].present?
        Rails.logger.error "[OPENWIFI][oauth2] Response :: ERROR :: #{res}"
      else
        $redis.hmset (@int_type.present? ? "OPENWIFI:SDK:USER:#{@int_type.id}" : 'OPENWIFI:SDK:USER'), 'access_token', res['access_token'], 'refresh_token', res['refresh_token'], 'expires_in', res['expires_in'], 'created_at', res['created'], 'username', res['username']
        if @int_type.present?
          @int_type.details ||= {}
          @int_type.details['response'] = res
          @int_type.save
        end
      end

      res
    end
  end
end
