--[[
  FinFeedAPI SEC REST API

  No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)

  The version of the OpenAPI document: v1
  Contact: support@apibricks.io
  Generated by: https://openapi-generator.tech
]]

--package openapiclient

local http_request = require "http.request"
local http_util = require "http.util"
local dkjson = require "dkjson"
local basexx = require "basexx"

-- model import
local openapiclient_mvc_problem_details = require "openapiclient.model.mvc_problem_details"
local openapiclient_mvc_validation_problem_details = require "openapiclient.model.mvc_validation_problem_details"

local file_download_api = {}
local file_download_api_mt = {
	__name = "file_download_api";
	__index = file_download_api;
}

local function new_file_download_api(authority, basePath, schemes)
	local schemes_map = {}
	for _,v in ipairs(schemes) do
		schemes_map[v] = v
	end
	local default_scheme = schemes_map.https or schemes_map.http
	local host, port = http_util.split_authority(authority, default_scheme)
	return setmetatable({
		host = host;
		port = port;
		basePath = basePath or "https://api.sec.finfeedapi.com";
		schemes = schemes_map;
		default_scheme = default_scheme;
		http_username = nil;
		http_password = nil;
		api_key = {};
		access_token = nil;
	}, file_download_api_mt)
end

function file_download_api:v1_download_get(accession_no, file_name)
	local req = http_request.new_from_uri({
		scheme = self.default_scheme;
		host = self.host;
		port = self.port;
		path = string.format("%s/v1/download?accession_no=%s&file_name=%s",
			self.basePath, http_util.encodeURIComponent(accession_no), http_util.encodeURIComponent(file_name));
	})

	-- set HTTP verb
	req.headers:upsert(":method", "GET")
	-- TODO: create a function to select proper content-type
	--local var_accept = { "application/octet-stream", "text/html", "application/xml", "text/plain", "application/pdf", "application/json" }
	req.headers:upsert("content-type", "application/octet-stream")

	-- api key in headers 'Authorization'
	if self.api_key['Authorization'] then
		req.headers:upsert("APIKey", self.api_key['Authorization'])
	end

	-- make the HTTP call
	local headers, stream, errno = req:go()
	if not headers then
		return nil, stream, errno
	end
	local http_status = headers:get(":status")
	if http_status:sub(1,1) == "2" then
		return nil, headers
	else
		local body, err, errno2 = stream:get_body_as_string()
		if not body then
			return nil, err, errno2
		end
		stream:shutdown()
		-- return the error message (http body)
		return nil, http_status, body
	end
end

return {
	new = new_file_download_api;
}
