package models

import (
	"errors"
	"oppmg/common/log"
	"time"

	"github.com/astaxie/beego/orm"
)

type Role struct {
	Id        int       `orm:"column(id);auto"`
	Name      string    `orm:"column(name);size(30)"`
	Pid       int       `orm:"column(pid)"`
	Types     int8      `orm:"column(types)"`
	CompanyId int       `orm:"column(company_id)"`
	Descript  string    `orm:"column(descript)"`
	CreateAt  time.Time `orm:"column(create_at);type(timestamp)"`
	DeleteAt  time.Time `orm:"column(delete_at);type(timestamp)"`
}

func (t *Role) TableName() string {
	return "role"
}

func init() {
	orm.RegisterModel(new(Role))
}

const (
	ROLETYPES_GROUP int8 = 1
	ROLETYPES_ROLE  int8 = 2
)

func (t *Role) ValidateTypes() bool {
	switch t.Types {
	case ROLETYPES_GROUP:
		return true
	case ROLETYPES_ROLE:
		return true
	}
	return false
}

func (t *Role) ValidatePid() error {
	roledata, err := GetRoleById(t.Pid)
	if err != nil {
		return err
	}
	if roledata.Types != ROLETYPES_GROUP {
		return errors.New("roledata.Types != ROLETYPES_GROUP")
	}
	if roledata.CompanyId != t.CompanyId {
		return errors.New("validate  companyId err")
	}
	return nil
}

// AddRole insert a new Role into database and returns
// last inserted Id on success.
func AddRole(m *Role) (id int64, err error) {
	o := orm.NewOrm()
	m.CreateAt = time.Now()
	id, err = o.Insert(m)
	return
}

// GetRoleById retrieves Role by Id. Returns error if
// Id doesn't exist
func GetRoleById(id int) (v *Role, err error) {
	o := orm.NewOrm()
	v = &Role{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// UpdateRole updates Role by Id and returns error if
// the record to be updated doesn't exist
func UpdateRoleById(m *Role, col []string) (err error) {
	o := orm.NewOrm()
	v := Role{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m, col...); err == nil {
			log.Debug("Number of records updated in database:%d", num)
		}
	}
	return
}

// DeleteRole deletes Role by Id and returns error if
// the record to be deleted doesn't exist
func DeleteRole(id int) (err error) {
	o := orm.NewOrm()
	v := Role{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		v.DeleteAt = time.Now()
		if num, err = o.Update(&v); err == nil {
			log.Debug("Number of records deleted in database:%d", num)
		}
	}
	return
}