package main

import (
	/*
		#include <stdint.h>
	*/
	"C"
	_ "image/png"
	"os"
	"strings"

	"bufio"
	"log"
	"net"

	"time"

	"github.com/kenshaw/escpos"
)

//export PrintImg
func PrintImg(printer *C.char, imagePath *C.char) *C.char {
	goPrinter := C.GoString(printer)
	goImagePath := C.GoString(imagePath)

	// printer := "tcp:192.168.100.151:9100"
	// printer := "usb:/dev/usb/lp1"
	var w *bufio.ReadWriter
	if strings.HasPrefix(goPrinter, "tcp:") {
		location := strings.TrimLeft(goPrinter, "tcp:")
		conn, err := net.Dial("tcp", location)
		if err != nil {
			log.Println("error dialing:", err.Error())
			return NewErr(err)
		}
		defer conn.Close()
		w = bufio.NewReadWriter(bufio.NewReader(conn), bufio.NewWriter(conn))
	} else if strings.HasPrefix(goPrinter, "usb:") {
		location := strings.TrimLeft(goPrinter, "usb:")
		f, err := os.OpenFile(location, os.O_RDWR, os.ModeDevice)
		if err != nil {
			log.Println("error OpenFile usb:", err.Error())
			return NewErr(err)
		}
		defer f.Close()
		w = bufio.NewReadWriter(bufio.NewReader(f), bufio.NewWriter(f))
	}
	prt := escpos.New(w)

	prt.Init()
	prt.SetSmooth(1)
	err := printImg(prt, goImagePath)
	if err != nil {
		return NewErr(err)
	}
	prt.Cut()
	prt.End()
	w.Flush()
	time.Sleep(100 * time.Millisecond)
	return NewOk(nil)
}
