package chain_service

import "bwallet/models"

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

	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) Add() error {
	chain := map[string]interface{}{
		"platform":    c.Platform,
		"address":     c.Address,
		"private_key": c.PrivateKey,
		"execer":      c.Execer,
		"token":       c.Token,
		"brower_url":  c.BrowerUrl,
		"fee":         c.Fee,
	}

	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,
		"execer":      c.Execer,
		"token":       c.Token,
		"brower_url":  c.BrowerUrl,
		"fee":         c.Fee,
	})
}

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
	}

	return maps
}
