package blowfishClient

import (
	"regexp"
	"ssp/blowfish"
	"ssp/logger"
	"strings"

	"crypt2go/ecb"
	"crypt2go/padding"
)

// Function for decrypting blowfish algorithm
func BlowfishDecrypt(pt, key []byte) string {
	block, err := blowfish.NewCipher(key)
	if err != nil {
		logger.Log.Println(err.Error())
	}
	mode := ecb.NewECBDecrypter(block)
	padder := padding.NewPkcs5Padding()
	pt, err = padder.Pad(pt) // padd last block of plaintext if block size less than block cipher size
	if err != nil {
		logger.Log.Println(err.Error())
	}
	ct := make([]byte, len(pt))
	mode.CryptBlocks(ct, pt)
	// Make a Regex to say we only want letters and numbers
	reg, err := regexp.Compile("[^0-9.]+")
	if err != nil {
		logger.Log.Println(err.Error())
	}
	dec := reg.ReplaceAllString(string(ct), "")
	return TrimSuffix(dec, "6")
}

// Function for encrypting blowfish algorithm
func BlowfishEncrypt(pt, key []byte) []byte {
	block, err := blowfish.NewCipher(key)
	if err != nil {
		logger.Log.Println(err.Error())
	}
	mode := ecb.NewECBEncrypter(block)
	padder := padding.NewPkcs5Padding()
	pt, err = padder.Pad(pt) // padd last block of plaintext if block size less than block cipher size
	if err != nil {
		logger.Log.Println(err.Error())
	}
	ct := make([]byte, len(pt))
	mode.CryptBlocks(ct, pt)
	return ct
}

// Trim symbols and unwanted values
func TrimSuffix(s, suffix string) string {
	if strings.HasSuffix(s, suffix) {
		s = s[:len(s)-len(suffix)]
	}
	return s
}
