package main

import (
	"bytes"
	"fmt"
	"net/url"

	"golang.org/x/text/encoding/korean"
	"golang.org/x/text/transform"
)

type LogEntry struct {
	Size     byte
	Type     uint8
	DateTime string
	On       uint8
	Address  [7]byte
	Area     [24]byte
	Device   [24]byte
}

func Deserialize(data []byte) (*LogEntry, error) {
	fmt.Printf("Data: %v\n", data)

	le := &LogEntry{}
	le.Size = data[0]
	if le.Size == 0 {
		return nil, fmt.Errorf("invalid data length: expected , got %d", le.Size)
	}

	le.Type = data[1]
	le.DateTime = fmt.Sprintf("%02d-%02d-%02d %02d:%02d:%02d", (int(data[2]) + 2000), data[3], data[4], data[5], data[6], data[7])
	le.On = data[8]
	copy(le.Address[:], data[9:16])
	copy(le.Area[:], data[16:40])
	copy(le.Device[:], data[40:])

	return le, nil
}

func decodeEUCKR(b []byte) (string, error) {
	decoder := korean.EUCKR.NewDecoder()
	result, _, err := transform.Bytes(decoder, b)
	if err != nil {
		return "", err
	}
	return string(result), nil
}

func convertToFormData(le *LogEntry) (url.Values, error) {
	area, err := decodeEUCKR(bytes.TrimRight(le.Area[:], "\x00"))
	if err != nil {
		return nil, err
	}

	device, err := decodeEUCKR(bytes.TrimRight(le.Device[:], "\x00"))
	if err != nil {
		return nil, err
	}

	var status string
	switch le.Type {
	case 1:
		le.Type = 6 // 화재
	case 2:
		le.Type = 2 // 고장
	case 3:
		le.Type = 3 // 설비
	case 4:
		le.Type = 4 // 출력
	}

	status = "해제"
	if le.On == 1 {
		status = "동작"
	}

	data := url.Values{}
	data.Set("callNo", config.CallNo)
	data.Set("type", fmt.Sprintf("%d", le.Type))
	data.Set("dateTime", le.DateTime)
	data.Set("status", status)
	data.Set("addr", fmt.Sprintf("%d%d-%d-%d%d%d-%d",
		le.Address[0], le.Address[1], le.Address[2],
		le.Address[3], le.Address[4], le.Address[5], le.Address[6]))
	data.Set("zoneNm", area)
	data.Set("deviceNm", device)

	return data, nil
}
