//
//  tank
//
//  Import and Playlist Daemon for autoradio project
//
//
//  Copyright (C) 2017-2018 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of tank.
//
//  tank is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  any later version.
//
//  tank is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with tank. If not, see <http://www.gnu.org/licenses/>.
//

package store

import (
	"errors"
	"os"
	"path/filepath"
)

func (st *Store) getGroupPath(group string) string {
	return filepath.Join(st.basePath, group)
}

// this will not fail if the group already exists
func (st *Store) CreateGroup(name string) (group *Group, err error) {
	groupDirPath := filepath.Join(st.basePath, name)
	if err := os.Mkdir(groupDirPath, 0755); err != nil {
		if !os.IsExist(err) {
			return nil, errors.New("unable to create directory for group '" + name + "': " + err.Error())
		}
		if stat, err := os.Stat(groupDirPath); err != nil {
			return nil, errors.New("unable to create directory for group '" + name + "': " + err.Error())
		} else if !stat.IsDir() {
			return nil, errors.New("unable to create directory for group '" + name + "': path exists and is not a directory")
		}
	}
	group = &Group{Name: name}
	err = st.db.FirstOrCreate(group).Error
	return
}

func (st *Store) CloneGroup(name, from string) error {
	// TODO:
	//   within transaction: {
	//     check if group already exists -> error
	//     st.CreateGroup(name)
	//     for file in files_of_group {
	//       create file in group <name> -> <dest-id>
	//       create hardlink for /store/base/path/<from>/<src-id> -> /store/base/path/<name>/<dest-id>
	//     }
	//   }
	return ErrNotImplented
}

// this will also remove all files and playlists belonging to the group!
func (st *Store) DeleteGroup(name string) error {
	if err := st.db.Delete(&Group{Name: name}).Error; err != nil {
		return err
	}
	return os.RemoveAll(st.getGroupPath(name))
}

func (st *Store) ListGroups() (groups Groups, err error) {
	err = st.db.Find(&groups).Error
	return
}