package routeupdater

import (
	"encoding/json"
	"fmt"

	"github.com/filtr/infrastructure/go/openvpn-route-updater/internal/logger"
	"github.com/pkg/errors"
	//"github.com/stretchr/testify/mock"
)

type testClient struct {
	//mock.Mock
	CliPath string
	log     logger.Logger
}

//SetRoute - dummy representation of update call for testing locally
func (c *testClient) SetRoute(user, routeID, routeValue string) error {
	response := `[True, {}]`

	if string(response) != `[True, {}]` {
		c.log.Warnf("Command output is not valid, got %v", response)
		return errors.New(fmt.Sprintf("Command output is not valid, got %v", response))
	}
	return nil
}

//RemoveRoute - dummy representation of remove call for testing locally
func (c *testClient) RemoveRoute(group, routeID string) error {
	response := `[True, {}]`

	if string(response) != `[True, {}]` {
		c.log.Warnf("Command output is not valid, got %v", response)
		return errors.New(fmt.Sprintf("Command output is not valid, got %v", response))
	}
	return nil
}

// GetGroupProps - predefined group response for testing
func (c *testClient) GetGroupProps(group string) (map[string]interface{}, error) {
	response := `{
		"Test group": {
		  "access_to.0": "+SUBNET:10.50.0.0/16",
		  "access_to.1": "+SUBNET:10.30.0.0/16",
		  "access_to.2": "+SUBNET:10.31.0.0/16",
		  "access_to.3": "+SUBNET:10.32.0.0/16",
		  "c2s_dest_s": "false",
		  "c2s_dest_v": "false",
		  "group_declare": "true",
		  "prop_autologin": "true",
		  "prop_deny": "false",
		  "prop_superuser": "false",
		  "type": "group"
		},
		"Test group 2": {
			"access_to.2": "+SUBNET:10.10.0.0/16",
			"access_to.0": "+SUBNET:10.50.0.0/16",
			"access_to.1": "+SUBNET:8.8.8.8/32",
			"c2s_dest_s": "false",
			"c2s_dest_v": "false",
			"group_declare": "true",
			"prop_autologin": "true",
			"prop_deny": "false",
			"prop_superuser": "false",
			"type": "group"
		  },
		"Test admins": {
			"access_to.0": "+SUBNET:10.50.0.0/16",
			"access_to.1": "+SUBNET:10.30.0.0/16",
			"access_to.2": "+SUBNET:10.31.0.0/16",
			"access_to.3": "+SUBNET:10.32.0.0/16",
			"access_to.4": "+SUBNET:10.10.0.0/16",
			"c2s_dest_s": "false",
			"c2s_dest_v": "false",
			"group_declare": "true",
			"prop_autologin": "true",
			"prop_deny": "false",
			"prop_superuser": "false",
			"type": "group"
		  }
	  }`
	var f interface{}
	err := json.Unmarshal([]byte(response), &f)
	if err != nil {
		return nil, err
	}
	m := f.(map[string]interface{})
	if _, exists := m[group]; exists {
		props := m[group].(map[string]interface{})
		return props, nil
	}
	return nil, errors.New(fmt.Sprintf("The group %v doesn't exist in OpenVPN", group))
}
