// Copyright (C) 2019 Marius Schellenberger

package db

import (
	"errors"
	"git.giftfish.de/ston1th/gowiki/pkg/core"
	"git.giftfish.de/ston1th/gowiki/pkg/log"
	"sort"
	"strings"
)

const sectionPrefix = "section/"

var (
	errSectionExists = errors.New("db: section already exist")
)

func (db *DB) GetSections() (secs core.Sections, err error) {
	err = db.store.ForEachPrefix(sectionPrefix, func(k string, _ []byte) error {
		s, err := db.GetSection(k)
		if err == nil {
			secs = append(secs, s)
		}
		return nil
	})
	sort.Sort(secs)
	return
}

func (db *DB) GetUserSections(username string) (sections map[string]bool, err error) {
	sections = make(map[string]bool)
	secs, err := db.GetSections()
	if err != nil {
		return
	}
	for _, s := range secs {
		if _, ok := core.Contains(username, s.Members); ok {
			sections[s.Name] = false
		}
	}
	return
}

func (db *DB) GetSection(section string) (s core.Section, err error) {
	err = db.store.Get(sectionPrefix+section, &s)
	return
}

func (db *DB) SectionExists(section string) error {
	return db.store.Get(sectionPrefix+section, nil)
}

func (db *DB) CreateSection(section string, members []string, user bool) error {
	section = userRe.ReplaceAllString(section, "")
	if err := db.SectionExists(section); err == nil {
		return errSectionExists
	}
	return db.UpdateSection(section, members, user)
}

func (db *DB) UpdateSection(section string, members []string, user bool) error {
	section = userRe.ReplaceAllString(section, "")
	if _, ok := core.Contains(section, reservedNames); ok {
		return errNameReserved
	}
	var m []string
	if user {
		m = append(m, section)
	} else {
		for _, v := range members {
			if v == "" {
				continue
			}
			if err := db.UserExists(v); err == nil {
				m = append(m, v)
			}
		}
	}
	return db.store.Set(sectionPrefix+section, &core.Section{section, user, m})
}

func (db *DB) DeleteSection(section string) error {
	if section == core.WikiSection {
		return errors.New("section '" + core.WikiSection + "' cannot be deleted")
	}
	err := db.SectionExists(section)
	if err != nil {
		return err
	}
	err = db.store.Delete(sectionPrefix + section)
	if err != nil {
		return err
	}
	section += "/"
	var pages []string
	db.store.ForEachPrefix(pagePrefix, func(k string, _ []byte) error {
		if strings.HasPrefix(k, section) {
			pages = append(pages, k)
		}
		return nil
	})
	for _, p := range pages {
		err := db.deletePage(p)
		if err != nil {
			log.Debugf("DeleteSection %s, %s", section, err)
		}
	}
	return nil
}
