package server

import (
	proto "git.xeserv.us/xena/route/proto"
	"github.com/Xe/ln"
	"golang.org/x/net/context"
)

// Route implements rout.RoutesServer for gRPC
type Route struct {
	*Server
}

// interface assertions
var (
	_ proto.RoutesServer = &Route{}
)

// Get fetches a route from the database.
func (r *Route) Get(ctx context.Context, req *proto.GetRouteRequest) (*proto.Route, error) {
	clitok, err := r.getAuth(ctx, "route:get")
	if err != nil {
		return nil, handleError(ctx, clitok, err, ln.F{"action": "Route.Get_getAuth"})
	}

	val, err := r.db.GetRoute(ctx, req.Host)
	if err != nil {
		ln.Error(err, ln.F{"action": "Route.Get"})

		return nil, err
	}

	if val.Creator != clitok.Owner {
		return nil, handleError(ctx, clitok, ErrNotAuthorized, ln.F{"action": "Route.Get_wrong_ownership"})
	}

	return val.AsProto(), nil
}

// GetAll fetches all of the routes that you own.
func (r *Route) GetAll(ctx context.Context, req *proto.Nil) (*proto.GetAllRoutesResponse, error) {
	clitok, err := r.getAuth(ctx, "route:getall")
	if err != nil {
		return nil, handleError(ctx, clitok, err, ln.F{"action": "Route.GetAll_getAuth"})
	}

	routes, err := r.db.GetAllRoutes(ctx, clitok.Owner)
	if err != nil {
		ln.Error(err, ln.F{"action": "Route.GetAll"})

		return nil, err
	}

	result := []*proto.Route{}

	// let result = apply routeAsProto routes
	for _, rt := range routes {
		result = append(result, rt.AsProto())
	}

	return &proto.GetAllRoutesResponse{
		Routes: result,
	}, nil
}

func (r *Route) Put(ctx context.Context, rt *proto.Route) (*proto.IDResponse, error) {
	clitok, err := r.getAuth(ctx, "route:put")
	if err != nil {
		return nil, handleError(ctx, clitok, err, ln.F{"action": "Route.Put_getAuth"})
	}

	drt, err := r.db.PutRoute(ctx, rt.Host, "http")
	if err != nil {
		ln.Error(err, ln.F{"action": "Route.Put"})

		return nil, err
	}

	return &proto.IDResponse{
		Id: drt.ID,
	}, nil
}

func (r *Route) Delete(ctx context.Context, rt *proto.Route) (*proto.IDResponse, error) {
	clitok, err := r.getAuth(ctx, "route:delete")
	if err != nil {
		return nil, handleError(ctx, clitok, err, ln.F{"action": "Route.Delete_getAuth"})
	}

	drt, err := r.db.GetRoute(ctx, rt.Host)
	if err != nil {
		ln.Error(err, ln.F{"action": "Route.Delete_getRoute_verify"})

		return nil, err
	}

	if drt.Creator != clitok.Owner {
		return nil, handleError(ctx, clitok, ErrNotAuthorized, ln.F{"action": "Route.Delete_not_authorized"})
	}

	err = r.db.DeleteRoute(ctx, rt.Id)
	f := drt.F()
	f["action"] = "Route.Delete_db.DeleteRoute"
	if err != nil {
		handleError(ctx, clitok, ErrNotAuthorized, f)
	}

	ln.Log(f, drt.F())

	return &proto.IDResponse{Id: rt.Id}, nil
}
