package orm

import (
	"fmt"
	"net/http"
	"time"

	"github.com/jinzhu/gorm"
	"gogs.carduccidante.edu.it/karmen/core/renderer"
)

type Log struct {
	gorm.Model

	Content string

	JobID uint
}

type Job struct {
	gorm.Model

	Name     string
	Document *Document

	Logs []*Log

	DocumentID uint

	Files []*File

	Start time.Time
	End   time.Time
}

func (s *Job) GetID() uint    { return s.ID }
func (j *Job) String() string { return fmt.Sprintf("Lavoro ID %d", j.ID) }

func (j *Job) Create(args map[string]string, r *http.Request) (interface{}, error) {
	return nil, fmt.Errorf("Not implemented")
}

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

func (j *Job) ReadAll(args map[string]string, r *http.Request) (interface{}, error) {
	var jobs []*Job
	if err := DB().Preload("Document").Order("start DESC").Find(&jobs).Error; err != nil {
		return nil, err
	}
	return jobs, nil
}

func (j *Job) Update(args map[string]string, r *http.Request) (interface{}, error) {
	if r.Method == "GET" {
		result, err := j.Read(args, r)
		if err != nil {
			return nil, err
		}

		job := result.(*Job)

		return job, nil
	} else {
		job, err := j.Read(args, r)
		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 = j.Read(args, r)
		if err != nil {
			return nil, err
		}

		return job.(*Job), nil
	}
}

func (j *Job) Delete(args map[string]string, r *http.Request) (interface{}, error) {
	job, err := j.Read(args, r)
	if err != nil {
		return nil, err
	}
	if err := DB().Unscoped().Delete(job.(*Job)).Error; 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
}
