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
	Icon       string
	Lock       int

	PageNum  int
	PageSize int
}

type Explore struct {
	BrowerUrl string `json:"brower_url,omitempty"` //浏览器链接
	Icon      string `json:"icon,omitempty"`       //图标
}

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) Explore() (*models.Explore, error) {
	tmp, err := models.GetExplore(c.Platform)
	if err != nil {
		return nil, err
	}

	var explore models.Explore
	explore.BrowerUrl = tmp.BrowerUrl
	explore.Icon = tmp.Icon

	return &explore, 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,
		"icon":        c.Icon,
		"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,
		"icon":        c.Icon,
		"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
}
