/*
 * Custom unmarshal to handle different query providers
 * based on provider type
 */
func (p *PanelDatasource) UnmarshalJSON(b []byte) error {
	var (
		tmp map[string]interface{}
		err error

		tVal string
		vOk  bool
	)

	if err = json.Unmarshal(b, &tmp); err != nil {
		return err
	}

	if tVal, vOk = tmp["type"].(string); !vOk {
		return fmt.Errorf("invalid provider type: %s", tmp["type"])
	}
	p.Type = providers.ProviderType(tVal)

	if tVal, vOk = tmp["alias"].(string); vOk {
		p.Alias = tVal
	}

	if tVal, vOk = tmp["transform"].(string); vOk {
		// v3
		p.Transform = tVal
	} else if tVal, vOk = tmp["yTransform"].(string); vOk {
		// v2
		p.Transform = tVal
	}

	if _, vOk := tmp["provider"]; vOk {
		// Marshal query back to bytes to be unmarshaled to it's specific type
		qBytes, _ := json.Marshal(tmp["provider"])
		p.Provider, err = providers.NewProvider(p.Type, qBytes)
	} else {
		// Default http
		p.Provider = providers.NewHttpProvider()
	}

	if p.Id == "" {
		p.Id = NewMetrilyxUUID()
	}
	return err
}
func (s *SchemaHTTPService) datasourceSchemaHandler(w http.ResponseWriter, r *http.Request) {
	parts := strings.Split(r.URL.Path, "/")
	if parts[len(parts)-1] == "" || parts[len(parts)-1] == "datasource" {
		/* list provider types */
		s.writeJsonReponse(w, r, providers.PROVIDER_TYPES, 200)
		return
	}

	var (
		providerType = providers.ProviderType(parts[len(parts)-1])
		panelDs      *schemas.PanelDatasource
	)

	panelDs, err := schemas.NewPanelDatasource(providerType)
	if err != nil {
		s.writeJsonReponse(w, r,
			fmt.Sprintf(`{"error": "provider not supported: '%s' %s"}`, providerType, err), 404)
		return
	}
	s.writeJsonReponse(w, r, panelDs, 200)
}
func Test_NewPanelDatasource_INVALID(t *testing.T) {
	if _, err := NewPanelDatasource(providers.ProviderType("hoopla")); err == nil {
		t.Errorf("Error check failed")
	}
}