package orm

import (
	"net/http"
	"strconv"
	"time"

	"github.com/jinzhu/gorm"
	"gogs.carducci-dante.gov.it/karmen/core/renderer"
)

type File struct {
	gorm.Model

	Path string

	JobID uint
}

type Job struct {
	gorm.Model

	Name     string
	Document *Document

	DocumentID uint

	Files []*File

	Start time.Time
	End   time.Time
}

func (s *Job) GetID() uint { return s.ID }

func GetFile(args map[string]string) (interface{}, error) {
	var job Job
	if err := DB().Preload("Document").Preload("Files").First(&job, args["id"]).Error; err != nil {
		return nil, err
	}
	return map[string]string{
		"filename":    args["filename"],
		"document_id": strconv.Itoa(int(job.DocumentID)),
		"id":          strconv.Itoa(int(job.ID)),
	}, nil
}

func GetJob(args map[string]string) (interface{}, error) {
	var job Job
	if err := DB().Preload("Document").Preload("Files").First(&job, args["id"]).Error; err != nil {
		return nil, err
	}
	return &job, nil
}

func UpdateJob(args map[string]string, r *http.Request) (IDer, error) {
	job, err := GetJob(args)
	if err != nil {
		return nil, err
	}

	err = renderer.Decode(job, r)
	if err != nil {
		return nil, err
	}

	_, err = SaveJob(job)
	if err != nil {
		return nil, err
	}
	job, err = GetJob(args)
	if err != nil {
		return nil, err
	}
	return job.(*Job), nil
}

func SaveJob(job interface{}) (interface{}, error) {
	if err := DB().Save(job).Error; err != nil {
		return nil, err
	}
	return job, nil
}
