package npd

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"net/url"

	"github.com/pquerna/ffjson/ffjson"

	"bitbucket.org/nemt/nemt-portal-api/application/third/npd/npdmodel"
	"bitbucket.org/nemt/nemt-portal-api/infra/config"
)

type providerService struct {
	cfg *config.Config
}

func newProviderService(cfg *config.Config) *providerService {
	return &providerService{
		cfg: cfg,
	}
}

func (c *providerService) GetProviders(searchParams npdmodel.ProviderSearchParams) (npdmodel.ProviderHeaderResponse, error) {
	providerURL := "https://api-pve.bcbs.com/Providers/V30%s"
	params := "?name=%s&alphaPrefix=BCB&lat=%v&long=%v&distance=%v&offset=%v&limit=%v&sortBy=%s&facetAcceptNewPatients=%s&facetGender=%s&facetExtendedOfficeHours=%s&facetProviderEntityName=%s&facetSummaryScore=%s&facetlanguage=%s&facetOfficelanguages=%s&facetHospitalAffiliations=%s&facetProviderAffiliations=%s"
	params = fmt.Sprintf(params, url.QueryEscape(searchParams.Name), searchParams.Latitude, searchParams.Longitude, searchParams.Distance, searchParams.Offset, searchParams.Limit, url.QueryEscape(searchParams.SortBy), url.QueryEscape(searchParams.FacetAcceptNewPatients), url.QueryEscape(searchParams.FacetGender), url.QueryEscape(searchParams.FacetExtendedOfficeHours), url.QueryEscape(searchParams.FacetProviderEntityName), url.QueryEscape(searchParams.FacetSummaryScore), url.QueryEscape(searchParams.FacetLanguage), url.QueryEscape(searchParams.FacetOfficeLanguages), url.QueryEscape(searchParams.FacetHospitalAffiliations), url.QueryEscape(searchParams.FacetProviderAffiliations))

	providerURL = fmt.Sprintf(providerURL, params)

	req, err := http.NewRequest("GET", providerURL, nil)
	if err != nil {
		return npdmodel.ProviderHeaderResponse{}, err
	}

	req.Header.Add("X-Api-Key", "sv6fs4dyh8macvuyyzgqs45w")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		return npdmodel.ProviderHeaderResponse{}, err
	}
	defer resp.Body.Close()

	bObject, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return npdmodel.ProviderHeaderResponse{}, err
	}

	var providers npdmodel.ProviderHeaderResponse
	if err := ffjson.Unmarshal(bObject, &providers); err != nil {
		return npdmodel.ProviderHeaderResponse{}, err
	}
	return providers, nil
}
