/*
Copyright (c) 2018 Vereign AG [https://www.vereign.com]

This is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

This program 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 Affero General Public License for more details.

You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

package handler

import (
	keyutils "code.vereign.com/code/key-storage-agent/utils"
	"code.vereign.com/code/viam-apis/data-storage-agent/client"
	"code.vereign.com/code/viam-apis/errors"
	"code.vereign.com/code/viam-apis/key-storage-agent/api"
	"golang.org/x/net/context"
)

func (s *KeyStorageServerImpl) SetAuthorized(ctx context.Context, in *api.SetAuthorizedRequest) (*api.SetAuthorizedResponse, error) {

	err := s.updateAll(ctx, in.Uuid, func(k *api.Key) { k.Unauthorized = !in.Value })
	if err != nil {
		return nil, errors.WrapInternal(err, "Could not authorize keys")
	}

	setAuthorizedResponse := &api.SetAuthorizedResponse{}
	return setAuthorizedResponse, nil
}

func (s *KeyStorageServerImpl) Destroy(ctx context.Context, in *api.DestroyRequest) (*api.DestroyResponse, error) {

	err := s.updateAll(ctx, in.Uuid, func(k *api.Key) { k.Destroyed = true })
	if err != nil {
		return nil, errors.WrapInternal(err, "Could not destroy keys")
	}

	destroyResponse := &api.DestroyResponse{}
	return destroyResponse, nil
}

func (s *KeyStorageServerImpl) Revoke(ctx context.Context, in *api.RevokeRequest) (*api.RevokeResponse, error) {

	err := s.updateAll(ctx, in.Uuid, func(k *api.Key) { k.Revoked = true })
	if err != nil {
		return nil, errors.WrapInternal(err, "Could not revoke keys")
	}

	revokeResponse := &api.RevokeResponse{}
	return revokeResponse, nil
}

func (s *KeyStorageServerImpl) Suspend(ctx context.Context, in *api.SuspendRequest) (*api.SuspendResponse, error) {

	err := s.updateAll(ctx, in.Uuid, func(k *api.Key) { k.Suspended = true })
	if err != nil {
		return nil, errors.WrapInternal(err, "Could not suspend keys")
	}

	suspendResponse := &api.SuspendResponse{}
	return suspendResponse, nil
}

func (s *KeyStorageServerImpl) Resume(ctx context.Context, in *api.ResumeRequest) (*api.ResumeResponse, error) {

	err := s.updateAll(ctx, in.Uuid, func(k *api.Key) { k.Suspended = false })
	if err != nil {
		return nil, errors.WrapInternal(err, "Could not resume keys")
	}

	resumeResponse := &api.ResumeResponse{}
	return resumeResponse, nil
}

func (s *KeyStorageServerImpl) Rename(ctx context.Context, in *api.RenameRequest) (*api.RenameResponse, error) {

	err := s.updateAll(ctx, in.Uuid, func(k *api.Key) { k.Name = in.Name })
	if err != nil {
		return nil, errors.WrapInternal(err, "Could not rename keys")
	}

	renameResponse := &api.RenameResponse{}
	return renameResponse, nil
}

func (s *KeyStorageServerImpl) updateAll(ctx context.Context, uuid string, updateFunc func(*api.Key)) error {
	auth := s.CreateAuthentication(ctx)

	client := keyutils.CreateDataStorageClient(auth)
	defer client.CloseClient()

	for _, kType := range []api.KeyType{api.KeyType_PRIVATE, api.KeyType_PUBLIC, api.KeyType_CERTIFICATE} {
		err := updateKey(client, uuid, kType, updateFunc)
		if err != nil {
			if !errors.Wraps(err, keyutils.ErrNoData) {
				return err
			}
		}
	}

	return nil
}

func updateKey(client *client.DataStorageClientImpl, uuid string, keyType api.KeyType, updateFunc func(*api.Key)) error {
	key, err := keyutils.GetKey(client, uuid, keyType)
	if err != nil {
		return err
	}

	updateFunc(key)

	_, _, err = client.PutData("keys", uuid+"/"+api.KeyType.String(keyType), key)
	if err != nil {
		return errors.WrapInternalFormat(err, "Could not store key %s", uuid+"/"+api.KeyType.String(keyType))
	}

	return nil
}