package main

import (
	"fmt"
	"bufio"
	"time"
	"os"
	"strings"
	"bytes"
	"encoding/binary"
	"example.com/genji"
)

func readData2( UserCode int32, dNr int16, data2Size uint16) bool {

	// allocate 4 bytes (uint32) and read the data length into it
	bDataLen := make([]byte, 4)
	if 4 == uint16(genji.Dongle_ReadData2( UserCode, bDataLen, 0, 4, dNr)){

		// convert bytes to uint32 dataLen
		buf := bytes.NewReader(bDataLen)

		var dataLen uint32
		err := binary.Read(buf, binary.LittleEndian, &dataLen)
		if err != nil {
			fmt.Println("binary.Read error")
			return false			
		}

		if( dataLen <= (uint32)(data2Size)){

			// allocate dataLen bytes and read data into it. Starting offset is 4
			data2 := make([]byte, dataLen)
			if dataLen == uint32(genji.Dongle_ReadData2( UserCode, data2, 4, (uint16)(dataLen), dNr)){	

				// display the data, assuing it is in the text format
				fmt.Println( string(data2))
			}else{
				fmt.Println("ReadData2 error( content )")
				return false;
			}
		}
	}else{
		fmt.Println( "ReadData2 Error(length)")
		return false
	}

	return true
}

func Data2test( UserCode int32, dNr int16) bool {

	fmt.Println("\n***** Data Area2 Test *****")

	//Data2 Area size
	var data2Size uint16 = uint16(genji.Dongle_MemSize2(dNr))
	fmt.Println("Data2 Size=", data2Size)
	time.Sleep(1 * time.Second)

	fmt.Println("\nCurrent Data2 contents( assuming it is in the plain text format):")

	if false == readData2( UserCode, dNr, data2Size ){
		return false
	}
	time.Sleep(1 * time.Second)

	reader := bufio.NewReader(os.Stdin)
	fmt.Println("\nEnter text to write to Data Area2: ")
	text, _ := reader.ReadString('\n') 

	if len(strings.TrimSpace(text)) == 0{
		fmt.Println("Skipping Data Area2 test")
		return true
	}

	// conver the input text to byte array
	bDataToWrite := []byte(text)
	
	// byte array length
	DataToWriteLen := uint32(len(bDataToWrite))

	//conver array length to into byte array (bs)
	bs := make([]byte, 4)
	binary.LittleEndian.PutUint32(bs, DataToWriteLen)

	// write byte array(length) + byte array(data)
	if (uint16)(DataToWriteLen+4) == uint16(genji.Dongle_WriteData2( UserCode, append(bs, bDataToWrite...), 0, (uint16)(DataToWriteLen+4), dNr)){
		fmt.Println( "Successfully Written to data2" )
		time.Sleep(1 * time.Second)

		// read the data just written
		fmt.Println("\nCurrent Data2 Content")
		if false == readData2(UserCode, dNr, data2Size){
			return false
		}
			

	}else{
		fmt.Println( "Failed to ]write to  data2")
		return false
	}
	time.Sleep(1 * time.Second)

	return true
}

