package models

import (
	"fmt"
	"log"
	"reflect"
	"regexp"
	"strconv"
)

var BtnCmd = map[string]int64{
	"user_add":       1,
	"user_edit":      2,
	"user_detete":    3,
	"users_list":     4,
	"group_add":      11,
	"group_edit":     12,
	"group_delete":   13,
	"groups_list":    14,
	"receipt_add":    21,
	"receipt_edit":   22,
	"receipt_delete": 23,
	"receipts_list":  24,
	"item_add":       31,
	"item_edit":      32,
	"item_delete":    33,
	"items_list":     34,
	"merchant":       96,
	"category":       97,
	"tax":            98,
	"total":          99,
}

// var btnPage = map[string]int64{
// 	"prev": 1,
// 	"next": 2,
// }

// TelegramBotCommand .
type TelegramBotCommand struct {
	Cmd        int64  // Internal Command ( user_add | user_edit | user_delete )
	ID         int64  // Internal UserID
	RefCmd     int64  // Internal Reference Command
	RefID      int64  // Internal Reference ID
	TelegramID int64  // Telegram UserID
	Pagination int64  // Pagination
	Extra      string // Internal String filed to pass Telegram FileID
}

// Unmarshal .
func (t *TelegramBotCommand) Unmarshal(c string) error {
	r := regexp.MustCompile(`^(?P<Cmd>.*)\|(?P<ID>.*)\|(?P<RefCmd>.*)\|(?P<RefID>.*)\|(?P<TelegramID>.*)\|(?P<Pagination>.*)\|(?P<Extra>.*)$`)
	m := r.FindStringSubmatch(c)

	res := make(map[string]string)
	for i, name := range r.SubexpNames() {
		if i != 0 && name != "" {
			res[name] = m[i]
		}
	}

	for k, val := range res {
		v := reflect.ValueOf(&t).Elem()
		f := reflect.Indirect(v).FieldByName(k)

		if !f.IsValid() {
			continue
		}
		if f.Type().Kind() == reflect.Int64 {
			age, err := strconv.Atoi(val)
			if err != nil {
				continue
			}
			f.SetInt(int64(age))
		} else {
			f.SetString(val)
		}
	}
	log.Printf("CALLBACK (UNMARSHAL) %d|%d|%d|%d|%d|%d|%s", t.Cmd, t.ID, t.RefCmd, t.RefID, t.TelegramID, t.Pagination, t.Extra)

	return nil
}

// Marshal .
func (t *TelegramBotCommand) Marshal() string {
	return fmt.Sprintf("%d|%d|%d|%d|%d|%d|%s", t.Cmd, t.ID, t.RefCmd, t.RefID, t.TelegramID, t.Pagination, t.Extra)
}

// String .
func String(t *TelegramBotCommand) string {
	return t.Marshal()
}
