package database

import (
	"fmt"
	"log"
	"time"

	"gorm.io/datatypes"
	"gorm.io/driver/postgres"
	"gorm.io/gorm"
	"gorm.io/gorm/clause"

	"github.com/moustachioed/dash/backend/database/models"
	"github.com/moustachioed/dash/backend/service"
)

type PgDatabase struct {
	Db *gorm.DB
}

func NewPgDatabase(host string, user string, password string, database string, port uint16) (service.DataStore, error) {
	db := &PgDatabase{}

	dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%d sslmode=disable", host, user, password, database, port)
	gdb, err := gorm.Open(postgres.Open(dsn), &gorm.Config{})

	if err != nil {
		log.Print(err.Error())
		return nil, err
	}
	log.Printf("Connected to database.")

	db.Db = gdb

	db.migrate()

	return db, nil
}

func (db *PgDatabase) migrate() {
	db.Db.AutoMigrate(&models.Journal{})
	db.Db.AutoMigrate(&models.PlanDay{})
	db.Db.AutoMigrate(&models.PlanWeek{})
	db.Db.AutoMigrate(&models.PlanMonth{})
	db.Db.AutoMigrate(&models.TrackingCategory{})
	db.Db.AutoMigrate(&models.TrackingItem{})
	db.Db.AutoMigrate(&models.Inbox{})
}

func (db *PgDatabase) WriteJournalEntry(entry interface{}) error {
	journal := entry.(models.Journal)
	err := db.Db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&journal).Error
	if err != nil {
		log.Print("Error writing journal entry to database.")
		return err
	}

	return nil
}

func (db *PgDatabase) GetJournalEntryForDate(date time.Time) (interface{}, error) {
	entry := models.Journal{Date: datatypes.Date(date)}
	db.Db.First(&entry)

	return entry, nil
}

func (db *PgDatabase) WritePlanDay(entry interface{}) error {
	planDay := entry.(models.PlanDay)
	err := db.Db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&planDay).Error
	if err != nil {
		log.Print("Error writing plan day to database.")
		return err
	}

	return nil
}

func (db *PgDatabase) GetPlanDayForDate(date time.Time) (interface{}, error) {
	entry := models.PlanDay{Date: datatypes.Date(date)}
	db.Db.First(&entry)

	return entry, nil
}

func (db *PgDatabase) WritePlanWeek(entry interface{}) error {
	planWeek := entry.(models.PlanWeek)
	err := db.Db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&planWeek).Error
	if err != nil {
		log.Print("Error writing plan week to database.")
		return err
	}

	return nil
}

func (db *PgDatabase) GetPlanWeekForDate(date time.Time) (interface{}, error) {
	entry := models.PlanWeek{Date: datatypes.Date(date)}
	db.Db.First(&entry)

	return entry, nil
}

func (db *PgDatabase) WritePlanMonth(entry interface{}) error {
	planMonth := entry.(models.PlanMonth)
	err := db.Db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&planMonth).Error
	if err != nil {
		log.Print("Error writing plan month to database.")
		return err
	}

	return nil
}

func (db *PgDatabase) GetPlanMonthForDate(date time.Time) (interface{}, error) {
	entry := models.PlanMonth{Date: datatypes.Date(date)}
	err := db.Db.First(&entry).Error
	if err != nil {
		log.Print("Error getting plan month from database.")
		return nil, err
	}

	return entry, nil
}

func (db *PgDatabase) GetTrackingItemsForDate(date time.Time) (interface{}, error) {
	entries := []models.TrackingItem{}
	err := db.Db.Where("date = ?", datatypes.Date(date)).Find(&entries).Error
	if err != nil {
		log.Print("Error getting tracking items from database.")
		return nil, err
	}

	return entries, nil
}

func (db *PgDatabase) WriteTrackingItems(entries interface{}) error {
	trackingItems := entries.([]models.TrackingItem)
	if len(trackingItems) == 0 {
		return nil
	}
	err := db.Db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&trackingItems).Error
	if err != nil {
		log.Print("Error writing tracking items to database.")
		return err
	}

	return nil
}

func (db *PgDatabase) GetTrackingCategories() (interface{}, error) {
	categories := []models.TrackingCategory{}
	err := db.Db.Find(&categories).Error
	if err != nil {
		log.Print("Error getting tracking categories from database.")
		return nil, err
	}

	return categories, nil
}

func (db *PgDatabase) WriteInboxItem(entry interface{}) error {
	inboxItem := entry.(models.Inbox)
	err := db.Db.Clauses(clause.OnConflict{UpdateAll: true}).Create(&inboxItem).Error
	if err != nil {
		log.Print("Error writing inbox item to database.")
		return err
	}

	return nil
}

func (db *PgDatabase) DeleteInboxItem(id int32) error {
	err := db.Db.Delete(&models.Inbox{}, id).Error
	if err != nil {
		log.Print("Error deleting inbox item from database.")
		return err
	}

	return nil
}

func (db *PgDatabase) GetInboxItems() ([]interface{}, error) {
	var inboxItems []models.Inbox
	db.Db.Find(&inboxItems)

	var interfaceSlice []interface{} = make([]interface{}, len(inboxItems))
	for i, d := range inboxItems {
		interfaceSlice[i] = d
	}

	return interfaceSlice, nil
}
