// Copyright Earl Warren <contact@earl-warren.org>
// Copyright Loïc Dachary <loic@dachary.org>
// SPDX-License-Identifier: MIT

package filesystem

import (
	"context"

	"code.forgejo.org/f3/gof3/v3/f3"
	helper_pullrequest "code.forgejo.org/f3/gof3/v3/forges/helpers/pullrequest"
	"code.forgejo.org/f3/gof3/v3/id"
	"code.forgejo.org/f3/gof3/v3/tree/generic"
)

type pullRequestDriver struct {
	nodeDriver
	h helper_pullrequest.Interface
}

func newPullRequestDriver(ctx context.Context, content f3.Interface) generic.NodeDriverInterface {
	n := newNodeDriver(content).(*nodeDriver)
	r := &pullRequestDriver{
		nodeDriver: *n,
	}
	r.h = helper_pullrequest.NewHelper(r)
	return r
}

func (o *pullRequestDriver) GetPullRequestRef() string {
	return ""
}

func (o *pullRequestDriver) GetPullRequestHead(context.Context) string {
	f := o.content.(*f3.PullRequest)
	return f.Head.Ref
}

func (o *pullRequestDriver) SetFetchFunc(fetchFunc func(ctx context.Context, url, ref string)) {
	f := o.content.(*f3.PullRequest)
	f.FetchFunc = fetchFunc
}

func (o *pullRequestDriver) Put(ctx context.Context) id.NodeID {
	return o.upsert(ctx)
}

func (o *pullRequestDriver) Patch(ctx context.Context) {
	o.upsert(ctx)
}

func (o *pullRequestDriver) upsert(ctx context.Context) id.NodeID {
	o.nodeDriver.upsert(ctx)
	return o.h.Fetch(ctx)
}

func (o *pullRequestDriver) Get(ctx context.Context) bool {
	if o.nodeDriver.Get(ctx) {
		o.h.Get(ctx)
		return true
	}
	return false
}
