package fic

import (
	"time"
)

// Event represents a challenge event.
type Event struct {
	Id   int64     `json:"id"`
	Kind string    `json:"kind"`
	Text string    `json:"txt"`
	Time time.Time `json:"time"`
}

// GetLastEvents returns the list of the last 10 events, sorted by date, last first
func GetLastEvents() ([]Event, error) {
	if rows, err := DBQuery("SELECT id_event, txt, kind, time FROM events ORDER BY time DESC LIMIT 10"); err != nil {
		return nil, err
	} else {
		defer rows.Close()

		var events = make([]Event, 0)
		for rows.Next() {
			var e Event
			if err := rows.Scan(&e.Id, &e.Text, &e.Kind, &e.Time); err != nil {
				return nil, err
			}
			events = append(events, e)
		}
		if err := rows.Err(); err != nil {
			return nil, err
		}

		return events, nil
	}
}

// GetEvents returns the list of all events, sorted by date, last first
func GetEvents() ([]*Event, error) {
	if rows, err := DBQuery("SELECT id_event, txt, kind, time FROM events ORDER BY time DESC"); err != nil {
		return nil, err
	} else {
		defer rows.Close()

		var events []*Event
		for rows.Next() {
			e := &Event{}
			if err := rows.Scan(&e.Id, &e.Text, &e.Kind, &e.Time); err != nil {
				return nil, err
			}
			events = append(events, e)
		}
		if err := rows.Err(); err != nil {
			return nil, err
		}

		return events, nil
	}
}

// GetEvent retrieves the event with the given id
func GetEvent(id int64) (e *Event, err error) {
	e = &Event{}
	err = DBQueryRow("SELECT id_event, txt, kind, time FROM events WHERE id_event=?", id).Scan(&e.Id, &e.Text, &e.Kind, &e.Time)
	return
}

// NewEvent creates a new event in the database and returns the corresponding structure
func NewEvent(txt string, kind string) (*Event, error) {
	if res, err := DBExec("INSERT INTO events (txt, kind, time) VALUES (?, ?, ?)", txt, kind, time.Now()); err != nil {
		return nil, err
	} else if eid, err := res.LastInsertId(); err != nil {
		return nil, err
	} else {
		return &Event{eid, txt, kind, time.Now()}, nil
	}
}

// Update applies modifications back to the database
func (e *Event) Update() (int64, error) {
	if res, err := DBExec("UPDATE events SET txt = ?, kind = ?, time = ? WHERE id_event = ?", e.Text, e.Kind, e.Time, e.Id); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}

// Delete the event from the database
func (e *Event) Delete() (int64, error) {
	if res, err := DBExec("DELETE FROM events WHERE id_event = ?", e.Id); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}

// ClearEvents removes all events from database
func ClearEvents() (int64, error) {
	if res, err := DBExec("DELETE FROM events"); err != nil {
		return 0, err
	} else if nb, err := res.RowsAffected(); err != nil {
		return 0, err
	} else {
		return nb, err
	}
}
