package database

import (
	"fmt"
	_ "github.com/lib/pq"
	"gitlab.com/kbr4/svevijesti/internal/model"
	"html/template"
	"math"
	"strings"
	"time"
)

func InsertArticle(store *Store, article model.ScrapedArticle) (err error) {
	query := `
  INSERT INTO articles
	   (title, content, slug, original_url, source_id)
	VALUES
	    ($1,$2,$3,$4,$5);`

	_, err = store.Exec(query, article.Title, article.Content, article.Slug, article.OriginalUrl, article.SourceId)
	if err != nil {
		return err
	}

	return nil
}

func IsSaved(store *Store, url string) bool {

	exists := false
	query, err := store.Prepare(`
     select exists(select 1 from articles where original_url = $1);
		 `)
	if err != nil {
		panic(err)
	}
	defer query.Close()

	row := query.QueryRow(url)
	err = row.Scan(&exists)
	if err != nil {
		panic(err)
	}
	return exists
}

func ArticlesForDay(store *Store, day time.Time) (articles []model.DisplayArticle, err error) {

	result := []model.DisplayArticle{}
	query, err := store.Prepare(`
     select id,title, content, slug, original_url, source_id, created_at from articles where created_at > $1 and created_at < $2 and LENGTH(content) > 10 order by id desc;
		 `)
	if err != nil {
		return result, err
	}
	defer query.Close()

	tomorrow := day.AddDate(0, 0, 1)
	todayDate := day.Format("2006-01-02")
	tomorrowDate := tomorrow.Format("2006-01-02")

	rows, err := query.Query(todayDate, tomorrowDate)
	if err != nil {
		return result, err
	}
	defer rows.Close()

	for rows.Next() {
		r := model.DisplayArticle{}
		err = rows.Scan(&r.ID, &r.Title, &r.Content, &r.Slug, &r.OriginalUrl, &r.SourceId, &r.CreatedAt)
		if err != nil {
			return result, err
		}

		ago := time.Now().Sub(r.CreatedAt)
		hours := ago.Hours()

		if hours < 1 {
			r.FormatedCreatedAt = fmt.Sprintf("Prije %d minuta.", int(math.Floor(ago.Minutes())))

		} else if hours > 24 {
			r.FormatedCreatedAt = r.CreatedAt.Format("02.01.2006. 15:04:05")
		} else {
			r.FormatedCreatedAt = fmt.Sprintf("Prije %d sati.", int(math.Floor(hours)))
		}
		r.SourceName = model.SourceName(r.SourceId)

		result = append(result, r)
	}

	return result, nil
}

func ArticleByID(store *Store, ID int, slug string) (article model.DisplayArticle, err error) {

	result := model.DisplayArticle{}
	query, err := store.Prepare(`
     select id,title, content, slug, original_url, source_id, created_at from articles where id = $1 and slug = $2;
		 `)
	if err != nil {
		return result, err
	}
	defer query.Close()

	row := query.QueryRow(ID, slug)
	if err != nil {
		return result, err
	}

	r := model.DisplayArticle{}
	content := ""
	err = row.Scan(&r.ID, &r.Title, &content, &r.Slug, &r.OriginalUrl, &r.SourceId, &r.CreatedAt)
	if err != nil {
		return result, err
	}

	ago := time.Now().Sub(r.CreatedAt)
	hours := ago.Hours()

	r.Content = template.HTML(strings.Replace(content, "\n", "<br>\n", -1))

	if hours < 1 {
		r.FormatedCreatedAt = fmt.Sprintf("Prije %d minuta.", int(math.Floor(ago.Minutes())))

	} else if hours > 24 {
		r.FormatedCreatedAt = r.CreatedAt.Format("02.01.2006. 15:04:05")
	} else {
		r.FormatedCreatedAt = fmt.Sprintf("Prije %d sati.", int(math.Floor(hours)))
	}
	r.SourceName = model.SourceName(r.SourceId)

	result = r

	return result, nil
}

func PreviousAndNextArticleUrlByID(store *Store, ID int) (nextUrl string, previousUrl string, err error) {

	nextResult, previousResult := "#", "#"
	query, err := store.Prepare(`
     select id,title, content, slug, original_url, source_id, created_at from articles where id < $1 and id > $2 order by id desc limit 1;
		 `)
	if err != nil {
		fmt.Println("Err 1:", err)
		return nextResult, previousResult, err
	}
	defer query.Close()

	row := query.QueryRow(ID, 0)
	if err != nil {
		fmt.Println("Err 2:", err)
		return nextResult, previousResult, err
	}

	r := model.DisplayArticle{}
	content := ""
	err = row.Scan(&r.ID, &r.Title, &content, &r.Slug, &r.OriginalUrl, &r.SourceId, &r.CreatedAt)
	if err != nil {
		return nextResult, previousResult, err
	}

	previousResult = fmt.Sprintf("/%d/%s", r.ID, r.Slug)

	query2, err := store.Prepare(`
     select id,title, content, slug, original_url, source_id, created_at from articles where id < $1 and id > $2 order by id asc limit 1;
		 `)
	if err != nil {
		fmt.Println("Err 1:", err)
		return nextResult, previousResult, err
	}
	defer query2.Close()

	row = query2.QueryRow(ID+1000, ID)
	if err != nil {
		fmt.Println("Err 3:", err)
		return nextResult, previousResult, err
	}

	content = ""
	err = row.Scan(&r.ID, &r.Title, &content, &r.Slug, &r.OriginalUrl, &r.SourceId, &r.CreatedAt)
	if err != nil {
		fmt.Println("Err 4:", err)
		return nextResult, previousResult, err
	}
	nextResult = fmt.Sprintf("/%d/%s", r.ID, r.Slug)

	return nextResult, previousResult, nil
}
