// Code generated by ent, DO NOT EDIT.

package ent

import (
	"context"
	"errors"
	"fmt"
	"time"

	"entgo.io/ent/dialect/sql"
	"entgo.io/ent/dialect/sql/sqlgraph"
	"entgo.io/ent/schema/field"
	"github.com/cloudreve/Cloudreve/v4/ent/predicate"
	"github.com/cloudreve/Cloudreve/v4/ent/task"
	"github.com/cloudreve/Cloudreve/v4/ent/user"
	"github.com/cloudreve/Cloudreve/v4/inventory/types"
)

// TaskUpdate is the builder for updating Task entities.
type TaskUpdate struct {
	config
	hooks    []Hook
	mutation *TaskMutation
}

// Where appends a list predicates to the TaskUpdate builder.
func (tu *TaskUpdate) Where(ps ...predicate.Task) *TaskUpdate {
	tu.mutation.Where(ps...)
	return tu
}

// SetUpdatedAt sets the "updated_at" field.
func (tu *TaskUpdate) SetUpdatedAt(t time.Time) *TaskUpdate {
	tu.mutation.SetUpdatedAt(t)
	return tu
}

// SetDeletedAt sets the "deleted_at" field.
func (tu *TaskUpdate) SetDeletedAt(t time.Time) *TaskUpdate {
	tu.mutation.SetDeletedAt(t)
	return tu
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (tu *TaskUpdate) SetNillableDeletedAt(t *time.Time) *TaskUpdate {
	if t != nil {
		tu.SetDeletedAt(*t)
	}
	return tu
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (tu *TaskUpdate) ClearDeletedAt() *TaskUpdate {
	tu.mutation.ClearDeletedAt()
	return tu
}

// SetType sets the "type" field.
func (tu *TaskUpdate) SetType(s string) *TaskUpdate {
	tu.mutation.SetType(s)
	return tu
}

// SetNillableType sets the "type" field if the given value is not nil.
func (tu *TaskUpdate) SetNillableType(s *string) *TaskUpdate {
	if s != nil {
		tu.SetType(*s)
	}
	return tu
}

// SetStatus sets the "status" field.
func (tu *TaskUpdate) SetStatus(t task.Status) *TaskUpdate {
	tu.mutation.SetStatus(t)
	return tu
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (tu *TaskUpdate) SetNillableStatus(t *task.Status) *TaskUpdate {
	if t != nil {
		tu.SetStatus(*t)
	}
	return tu
}

// SetPublicState sets the "public_state" field.
func (tu *TaskUpdate) SetPublicState(tps *types.TaskPublicState) *TaskUpdate {
	tu.mutation.SetPublicState(tps)
	return tu
}

// SetPrivateState sets the "private_state" field.
func (tu *TaskUpdate) SetPrivateState(s string) *TaskUpdate {
	tu.mutation.SetPrivateState(s)
	return tu
}

// SetNillablePrivateState sets the "private_state" field if the given value is not nil.
func (tu *TaskUpdate) SetNillablePrivateState(s *string) *TaskUpdate {
	if s != nil {
		tu.SetPrivateState(*s)
	}
	return tu
}

// ClearPrivateState clears the value of the "private_state" field.
func (tu *TaskUpdate) ClearPrivateState() *TaskUpdate {
	tu.mutation.ClearPrivateState()
	return tu
}

// SetUserTasks sets the "user_tasks" field.
func (tu *TaskUpdate) SetUserTasks(i int) *TaskUpdate {
	tu.mutation.SetUserTasks(i)
	return tu
}

// SetNillableUserTasks sets the "user_tasks" field if the given value is not nil.
func (tu *TaskUpdate) SetNillableUserTasks(i *int) *TaskUpdate {
	if i != nil {
		tu.SetUserTasks(*i)
	}
	return tu
}

// ClearUserTasks clears the value of the "user_tasks" field.
func (tu *TaskUpdate) ClearUserTasks() *TaskUpdate {
	tu.mutation.ClearUserTasks()
	return tu
}

// SetUserID sets the "user" edge to the User entity by ID.
func (tu *TaskUpdate) SetUserID(id int) *TaskUpdate {
	tu.mutation.SetUserID(id)
	return tu
}

// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (tu *TaskUpdate) SetNillableUserID(id *int) *TaskUpdate {
	if id != nil {
		tu = tu.SetUserID(*id)
	}
	return tu
}

// SetUser sets the "user" edge to the User entity.
func (tu *TaskUpdate) SetUser(u *User) *TaskUpdate {
	return tu.SetUserID(u.ID)
}

// Mutation returns the TaskMutation object of the builder.
func (tu *TaskUpdate) Mutation() *TaskMutation {
	return tu.mutation
}

// ClearUser clears the "user" edge to the User entity.
func (tu *TaskUpdate) ClearUser() *TaskUpdate {
	tu.mutation.ClearUser()
	return tu
}

// Save executes the query and returns the number of nodes affected by the update operation.
func (tu *TaskUpdate) Save(ctx context.Context) (int, error) {
	if err := tu.defaults(); err != nil {
		return 0, err
	}
	return withHooks(ctx, tu.sqlSave, tu.mutation, tu.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (tu *TaskUpdate) SaveX(ctx context.Context) int {
	affected, err := tu.Save(ctx)
	if err != nil {
		panic(err)
	}
	return affected
}

// Exec executes the query.
func (tu *TaskUpdate) Exec(ctx context.Context) error {
	_, err := tu.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (tu *TaskUpdate) ExecX(ctx context.Context) {
	if err := tu.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (tu *TaskUpdate) defaults() error {
	if _, ok := tu.mutation.UpdatedAt(); !ok {
		if task.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized task.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := task.UpdateDefaultUpdatedAt()
		tu.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (tu *TaskUpdate) check() error {
	if v, ok := tu.mutation.Status(); ok {
		if err := task.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Task.status": %w`, err)}
		}
	}
	return nil
}

func (tu *TaskUpdate) sqlSave(ctx context.Context) (n int, err error) {
	if err := tu.check(); err != nil {
		return n, err
	}
	_spec := sqlgraph.NewUpdateSpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt))
	if ps := tu.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := tu.mutation.UpdatedAt(); ok {
		_spec.SetField(task.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := tu.mutation.DeletedAt(); ok {
		_spec.SetField(task.FieldDeletedAt, field.TypeTime, value)
	}
	if tu.mutation.DeletedAtCleared() {
		_spec.ClearField(task.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := tu.mutation.GetType(); ok {
		_spec.SetField(task.FieldType, field.TypeString, value)
	}
	if value, ok := tu.mutation.Status(); ok {
		_spec.SetField(task.FieldStatus, field.TypeEnum, value)
	}
	if value, ok := tu.mutation.PublicState(); ok {
		_spec.SetField(task.FieldPublicState, field.TypeJSON, value)
	}
	if value, ok := tu.mutation.PrivateState(); ok {
		_spec.SetField(task.FieldPrivateState, field.TypeString, value)
	}
	if tu.mutation.PrivateStateCleared() {
		_spec.ClearField(task.FieldPrivateState, field.TypeString)
	}
	if tu.mutation.CorrelationIDCleared() {
		_spec.ClearField(task.FieldCorrelationID, field.TypeUUID)
	}
	if tu.mutation.UserCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   task.UserTable,
			Columns: []string{task.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := tu.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   task.UserTable,
			Columns: []string{task.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	if n, err = sqlgraph.UpdateNodes(ctx, tu.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{task.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return 0, err
	}
	tu.mutation.done = true
	return n, nil
}

// TaskUpdateOne is the builder for updating a single Task entity.
type TaskUpdateOne struct {
	config
	fields   []string
	hooks    []Hook
	mutation *TaskMutation
}

// SetUpdatedAt sets the "updated_at" field.
func (tuo *TaskUpdateOne) SetUpdatedAt(t time.Time) *TaskUpdateOne {
	tuo.mutation.SetUpdatedAt(t)
	return tuo
}

// SetDeletedAt sets the "deleted_at" field.
func (tuo *TaskUpdateOne) SetDeletedAt(t time.Time) *TaskUpdateOne {
	tuo.mutation.SetDeletedAt(t)
	return tuo
}

// SetNillableDeletedAt sets the "deleted_at" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableDeletedAt(t *time.Time) *TaskUpdateOne {
	if t != nil {
		tuo.SetDeletedAt(*t)
	}
	return tuo
}

// ClearDeletedAt clears the value of the "deleted_at" field.
func (tuo *TaskUpdateOne) ClearDeletedAt() *TaskUpdateOne {
	tuo.mutation.ClearDeletedAt()
	return tuo
}

// SetType sets the "type" field.
func (tuo *TaskUpdateOne) SetType(s string) *TaskUpdateOne {
	tuo.mutation.SetType(s)
	return tuo
}

// SetNillableType sets the "type" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableType(s *string) *TaskUpdateOne {
	if s != nil {
		tuo.SetType(*s)
	}
	return tuo
}

// SetStatus sets the "status" field.
func (tuo *TaskUpdateOne) SetStatus(t task.Status) *TaskUpdateOne {
	tuo.mutation.SetStatus(t)
	return tuo
}

// SetNillableStatus sets the "status" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableStatus(t *task.Status) *TaskUpdateOne {
	if t != nil {
		tuo.SetStatus(*t)
	}
	return tuo
}

// SetPublicState sets the "public_state" field.
func (tuo *TaskUpdateOne) SetPublicState(tps *types.TaskPublicState) *TaskUpdateOne {
	tuo.mutation.SetPublicState(tps)
	return tuo
}

// SetPrivateState sets the "private_state" field.
func (tuo *TaskUpdateOne) SetPrivateState(s string) *TaskUpdateOne {
	tuo.mutation.SetPrivateState(s)
	return tuo
}

// SetNillablePrivateState sets the "private_state" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillablePrivateState(s *string) *TaskUpdateOne {
	if s != nil {
		tuo.SetPrivateState(*s)
	}
	return tuo
}

// ClearPrivateState clears the value of the "private_state" field.
func (tuo *TaskUpdateOne) ClearPrivateState() *TaskUpdateOne {
	tuo.mutation.ClearPrivateState()
	return tuo
}

// SetUserTasks sets the "user_tasks" field.
func (tuo *TaskUpdateOne) SetUserTasks(i int) *TaskUpdateOne {
	tuo.mutation.SetUserTasks(i)
	return tuo
}

// SetNillableUserTasks sets the "user_tasks" field if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableUserTasks(i *int) *TaskUpdateOne {
	if i != nil {
		tuo.SetUserTasks(*i)
	}
	return tuo
}

// ClearUserTasks clears the value of the "user_tasks" field.
func (tuo *TaskUpdateOne) ClearUserTasks() *TaskUpdateOne {
	tuo.mutation.ClearUserTasks()
	return tuo
}

// SetUserID sets the "user" edge to the User entity by ID.
func (tuo *TaskUpdateOne) SetUserID(id int) *TaskUpdateOne {
	tuo.mutation.SetUserID(id)
	return tuo
}

// SetNillableUserID sets the "user" edge to the User entity by ID if the given value is not nil.
func (tuo *TaskUpdateOne) SetNillableUserID(id *int) *TaskUpdateOne {
	if id != nil {
		tuo = tuo.SetUserID(*id)
	}
	return tuo
}

// SetUser sets the "user" edge to the User entity.
func (tuo *TaskUpdateOne) SetUser(u *User) *TaskUpdateOne {
	return tuo.SetUserID(u.ID)
}

// Mutation returns the TaskMutation object of the builder.
func (tuo *TaskUpdateOne) Mutation() *TaskMutation {
	return tuo.mutation
}

// ClearUser clears the "user" edge to the User entity.
func (tuo *TaskUpdateOne) ClearUser() *TaskUpdateOne {
	tuo.mutation.ClearUser()
	return tuo
}

// Where appends a list predicates to the TaskUpdate builder.
func (tuo *TaskUpdateOne) Where(ps ...predicate.Task) *TaskUpdateOne {
	tuo.mutation.Where(ps...)
	return tuo
}

// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (tuo *TaskUpdateOne) Select(field string, fields ...string) *TaskUpdateOne {
	tuo.fields = append([]string{field}, fields...)
	return tuo
}

// Save executes the query and returns the updated Task entity.
func (tuo *TaskUpdateOne) Save(ctx context.Context) (*Task, error) {
	if err := tuo.defaults(); err != nil {
		return nil, err
	}
	return withHooks(ctx, tuo.sqlSave, tuo.mutation, tuo.hooks)
}

// SaveX is like Save, but panics if an error occurs.
func (tuo *TaskUpdateOne) SaveX(ctx context.Context) *Task {
	node, err := tuo.Save(ctx)
	if err != nil {
		panic(err)
	}
	return node
}

// Exec executes the query on the entity.
func (tuo *TaskUpdateOne) Exec(ctx context.Context) error {
	_, err := tuo.Save(ctx)
	return err
}

// ExecX is like Exec, but panics if an error occurs.
func (tuo *TaskUpdateOne) ExecX(ctx context.Context) {
	if err := tuo.Exec(ctx); err != nil {
		panic(err)
	}
}

// defaults sets the default values of the builder before save.
func (tuo *TaskUpdateOne) defaults() error {
	if _, ok := tuo.mutation.UpdatedAt(); !ok {
		if task.UpdateDefaultUpdatedAt == nil {
			return fmt.Errorf("ent: uninitialized task.UpdateDefaultUpdatedAt (forgotten import ent/runtime?)")
		}
		v := task.UpdateDefaultUpdatedAt()
		tuo.mutation.SetUpdatedAt(v)
	}
	return nil
}

// check runs all checks and user-defined validators on the builder.
func (tuo *TaskUpdateOne) check() error {
	if v, ok := tuo.mutation.Status(); ok {
		if err := task.StatusValidator(v); err != nil {
			return &ValidationError{Name: "status", err: fmt.Errorf(`ent: validator failed for field "Task.status": %w`, err)}
		}
	}
	return nil
}

func (tuo *TaskUpdateOne) sqlSave(ctx context.Context) (_node *Task, err error) {
	if err := tuo.check(); err != nil {
		return _node, err
	}
	_spec := sqlgraph.NewUpdateSpec(task.Table, task.Columns, sqlgraph.NewFieldSpec(task.FieldID, field.TypeInt))
	id, ok := tuo.mutation.ID()
	if !ok {
		return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Task.id" for update`)}
	}
	_spec.Node.ID.Value = id
	if fields := tuo.fields; len(fields) > 0 {
		_spec.Node.Columns = make([]string, 0, len(fields))
		_spec.Node.Columns = append(_spec.Node.Columns, task.FieldID)
		for _, f := range fields {
			if !task.ValidColumn(f) {
				return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
			}
			if f != task.FieldID {
				_spec.Node.Columns = append(_spec.Node.Columns, f)
			}
		}
	}
	if ps := tuo.mutation.predicates; len(ps) > 0 {
		_spec.Predicate = func(selector *sql.Selector) {
			for i := range ps {
				ps[i](selector)
			}
		}
	}
	if value, ok := tuo.mutation.UpdatedAt(); ok {
		_spec.SetField(task.FieldUpdatedAt, field.TypeTime, value)
	}
	if value, ok := tuo.mutation.DeletedAt(); ok {
		_spec.SetField(task.FieldDeletedAt, field.TypeTime, value)
	}
	if tuo.mutation.DeletedAtCleared() {
		_spec.ClearField(task.FieldDeletedAt, field.TypeTime)
	}
	if value, ok := tuo.mutation.GetType(); ok {
		_spec.SetField(task.FieldType, field.TypeString, value)
	}
	if value, ok := tuo.mutation.Status(); ok {
		_spec.SetField(task.FieldStatus, field.TypeEnum, value)
	}
	if value, ok := tuo.mutation.PublicState(); ok {
		_spec.SetField(task.FieldPublicState, field.TypeJSON, value)
	}
	if value, ok := tuo.mutation.PrivateState(); ok {
		_spec.SetField(task.FieldPrivateState, field.TypeString, value)
	}
	if tuo.mutation.PrivateStateCleared() {
		_spec.ClearField(task.FieldPrivateState, field.TypeString)
	}
	if tuo.mutation.CorrelationIDCleared() {
		_spec.ClearField(task.FieldCorrelationID, field.TypeUUID)
	}
	if tuo.mutation.UserCleared() {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   task.UserTable,
			Columns: []string{task.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		_spec.Edges.Clear = append(_spec.Edges.Clear, edge)
	}
	if nodes := tuo.mutation.UserIDs(); len(nodes) > 0 {
		edge := &sqlgraph.EdgeSpec{
			Rel:     sqlgraph.M2O,
			Inverse: true,
			Table:   task.UserTable,
			Columns: []string{task.UserColumn},
			Bidi:    false,
			Target: &sqlgraph.EdgeTarget{
				IDSpec: sqlgraph.NewFieldSpec(user.FieldID, field.TypeInt),
			},
		}
		for _, k := range nodes {
			edge.Target.Nodes = append(edge.Target.Nodes, k)
		}
		_spec.Edges.Add = append(_spec.Edges.Add, edge)
	}
	_node = &Task{config: tuo.config}
	_spec.Assign = _node.assignValues
	_spec.ScanValues = _node.scanValues
	if err = sqlgraph.UpdateNode(ctx, tuo.driver, _spec); err != nil {
		if _, ok := err.(*sqlgraph.NotFoundError); ok {
			err = &NotFoundError{task.Label}
		} else if sqlgraph.IsConstraintError(err) {
			err = &ConstraintError{msg: err.Error(), wrap: err}
		}
		return nil, err
	}
	tuo.mutation.done = true
	return _node, nil
}
