package swClient

import (
	"errors"
	"fmt"
	"strings"

	switchAPI "github.rackspace.com/gorax/clients/pysshAPI"
)

func (s *Switch) Ping(ip, vrf string) (*string, error) {
	if vrf != "" {
		return s.SwitchDirectRun(fmt.Sprintf("ping %s vrf %s", ip, vrf))
	}
	return s.SwitchDirectRun("ping %s")
}

func (s *Switch) ARP(ip, vrf string) (*string, error) {
	if vrf != "" {
		return s.SwitchDirectRun(fmt.Sprintf("show ip arp %s vrf %s", ip, vrf))
	}
	return s.SwitchDirectRun("show ip arp %s")
}

func (s *Switch) DirectSwitchConfig() (*string, error) {
	return s.SwitchDirectRun("show run")
}

func (s *Switch) DirectIntStatus() (*string, error) {
	return s.SwitchDirectRun("show interface status")
}

func (s *Switch) DirectFullMAC() (*string, error) {
	return s.SwitchDirectRun("show mac address-table")
}

func (s *Switch) DirectPortStatus(port string) (*string, error) {
	return s.SwitchDirectRun("show int " + port)
}

func (s *Switch) DirectMACVlan(vlan string) (*string, error) {
	return s.SwitchDirectRun("show mac address-table vlan " + vlan)
}

func (s *Switch) DirectMACPort(port string) (*string, error) {
	return s.SwitchDirectRun("show mac address-table interface " + port)
}

func (s *Switch) SwitchDirectRun(command string) (*string, error) {
	commands := switchAPI.MarshalCommands([]string{command}, *s.Name)
	res, err := switchAPI.SwitchPostCommands(commands, *s.Name, *s.token)
	if err != nil {
		return nil, err
	}

	conf := res.FindResponse(command)
	if conf == nil {
		return nil, errors.New("Switch SSH returned no response for " + command)
	}

	return conf, nil
}

func (s *Switch) SwitchDirectCommands(cmdList []string) (*switchAPI.SwitchCommandRequest, error) {
	commands := switchAPI.MarshalCommands(cmdList, *s.Name)
	res, err := switchAPI.SwitchPostCommands(commands, *s.Name, *s.token)
	if err != nil {
		return nil, err
	}

	return res, nil
}

func (s *Switch) ConfT() error {
	commands := switchAPI.MarshalCommands([]string{"conf t"}, *s.Name)
	res, err := switchAPI.SwitchPostCommands(commands, *s.Name, *s.token)
	if err != nil {
		return err
	}

	conf := res.FindResponse("conf t")
	if conf == nil {
		return errors.New("Switch SSH returned no response for " + "conf t")
	}

	if strings.Contains(*conf, "(config") {
		return nil
	}

	return errors.New("Unable to find config prompt, received " + *conf)

}

func (s *Switch) EndConf() error {
	commands := switchAPI.MarshalCommands([]string{"end"}, *s.Name)
	res, err := switchAPI.SwitchPostCommands(commands, *s.Name, *s.token)
	if err != nil {
		return err
	}

	conf := res.FindResponse("end")
	if conf == nil {
		return errors.New("Switch SSH returned no response for " + "end")
	}

	return nil

}
