package chain_service

import "bwallet/models"

type Chain struct {
	ID         int
	Platform   string
	Address    string
	PrivateKey string
	Exer       string
	Token      string
	Fee        float32
	BrowerUrl  string
	Lock       int

	PageNum  int
	PageSize int
}

func (c *Chain) Get() (*models.Chain, error) {
	chain, err := models.GetChain(c.ID)
	if err != nil {
		return nil, err
	}

	return chain, nil
}

func (c *Chain) GetAll() ([]*models.Chain, error) {
	var chains []*models.Chain

	chains, err := models.GetChains(c.PageNum, c.PageSize, c.getMaps())
	if err != nil {
		return nil, err
	}

	return chains, nil
}

func (c *Chain) GetUserChain() ([]*models.UserChain, error) {
	var chains []*models.UserChain

	chains, err := models.GetUserChains(c.getMaps())
	if err != nil {
		return nil, err
	}

	return chains, nil
}

func (c *Chain) Add() error {
	chain := map[string]interface{}{
		"platform":    c.Platform,
		"address":     c.Address,
		"private_key": c.PrivateKey,
		"exer":        c.Exer,
		"token":       c.Token,
		"brower_url":  c.BrowerUrl,
		"fee":         c.Fee,
		"lock":        c.Lock,
	}

	if err := models.AddChain(chain); err != nil {
		return err
	}

	return nil
}

func (c *Chain) Edit() error {
	return models.EditChain(c.ID, map[string]interface{}{
		"platform":    c.Platform,
		"address":     c.Address,
		"private_key": c.PrivateKey,
		"exer":        c.Exer,
		"token":       c.Token,
		"brower_url":  c.BrowerUrl,
		"fee":         c.Fee,
		"lock":        c.Lock,
	})
}

func (c *Chain) ExistById() (bool, error) {
	return models.ExistChainById(c.ID)
}

func (c *Chain) Count() (int, error) {
	return models.GetChainTotal(c.getMaps())
}

func (c *Chain) Delete() error {
	return models.DeleteChain(c.ID)
}

func (c *Chain) getMaps() (map[string]interface{}) {
	maps := make(map[string]interface{})

	if c.ID != 0 {
		maps["id"] = c.ID
	}

	if c.Platform != "" {
		maps["platform"] = c.Platform
	}

	return maps
}
