// Copyright 2019 the Drone Authors. All rights reserved.
// Use of this source code is governed by the Blue Oak Model License
// that can be found in the LICENSE file.

package plugin

import (
	"context"
	"git.entr0py.de/garionion/drone-yaml-server/repo"
	"github.com/sirupsen/logrus"
	"time"

	"github.com/drone/drone-go/drone"
	"github.com/drone/drone-go/plugin/config"
)

// TODO replace or remove
const defaultPipeline = `
kind: pipeline
name: default

steps:
- name: build
  image: golang
  commands:
  - go build
  - go test -v
`

// New returns a new config plugin.
func New(repository, branch, token string, frequency time.Duration) config.Plugin {
	repos := repo.Repos{&repo.Repo{
		URL:       repository,
		Token:     token,
		Branch:    branch,
		Frequency: frequency,
	}}
	repos.Init()

	return &plugin{
		repos: repos,
	}
}

type plugin struct {
	repos repo.Repos
}

func (p *plugin) Find(ctx context.Context, req *config.Request) (*drone.Config, error) {
	if req.Repo.Namespace == "some-organization" {
		return &drone.Config{
			Data: defaultPipeline,
		}, nil
	}

	configuration, err := p.repos.GetConfiguration(req.Repo.HTTPURL)
	if err != nil {
		logrus.Error(err)
		return nil, err
	}
	if configuration != "" {
		return &drone.Config{
			Data: configuration,
		}, nil
	}

	return nil, nil
}