package ym485

import (
	"encoding/hex"
	"fmt"
)

// ASCII2Lbcd lbcd adds necessary "0" on the left side of byte array, if number of bytes is odd
func ASCII2Lbcd(data []byte) ([]byte, error) {
	if len(data)%2 != 0 {
		return bcd(append(data, "0"...))
	}
	return bcd(data)
}

// ASCII2Rbcd rbcd adds necessary "0" on the left side of byte array, if number of bytes is odd
func ASCII2Rbcd(data []byte) ([]byte, error) {
	if len(data)%2 != 0 {
		return bcd(append([]byte("0"), data...))
	}
	return bcd(data)
}

// Encode numeric in ascii into bsd (be sure len(data) % 2 == 0)
func bcd(data []byte) ([]byte, error) {
	out := make([]byte, len(data)/2+1)
	n, err := hex.Decode(out, data)
	if err != nil {
		return nil, err
	}
	return out[:n], nil
}

func Lbcd2ASCII(data []byte) []byte {
	r := bcd2Ascii(data)
	if r[len(r)-1] == 48 {
		r = r[:len(r)-1]
	}
	return r
}

func Rbcd2ASCII(data []byte) []byte {
	r := bcd2Ascii(data)
	if r[0] == 48 {
		return r[1:]
	}
	return r
}

func bcd2Ascii(data []byte) []byte {
	out := make([]byte, len(data)*2)
	n := hex.Encode(out, data)
	return out[:n]
}

func Dec2Rbcd(dec int) ([]byte, error) {
	return ASCII2Rbcd([]byte(fmt.Sprint(dec)))
}

func Dec2Lbcd(dec int) ([]byte, error) {
	return ASCII2Lbcd([]byte(fmt.Sprint(dec)))
}

func Rotate(ss []byte) []byte {
	ret := make([]byte, len(ss))
	copy(ret, ss)
	left, rigth := 0, 0
	if len(ret)%2 == 0 {
		left = len(ret)/2 - 1
		rigth = len(ret) / 2
	} else {
		left = len(ret)/2 - 1
		rigth = len(ret)/2 + 1
	}
	for ; left >= 0 || rigth <= len(ret)-1; left, rigth = left-1, rigth+1 {
		ret[left], ret[rigth] = ret[rigth], ret[left]
	}
	return ret
}
