package usersroute

import (
	b64 "encoding/base64"
	"fmt"
	"math/rand"
	"sync"
	"time"

	"bitbucket.org/nemt/nemt-portal-api/application/applicationservice"
	"bitbucket.org/nemt/nemt-portal-api/application/third/eligibility/bcbsi"
	"bitbucket.org/nemt/nemt-portal-api/application/viewmodel"
	"bitbucket.org/nemt/nemt-portal-api/domain"
	"bitbucket.org/nemt/nemt-portal-api/infra/auth"
	"bitbucket.org/nemt/nemt-portal-api/infra/cache"
	"bitbucket.org/nemt/nemt-portal-api/infra/config"
	"bitbucket.org/nemt/nemt-portal-api/server/authorization"
	"bitbucket.org/nemt/nemt-portal-api/server/router/routeutils"
	"bitbucket.org/nemt/nemt-portal-api/server/validation"
	"github.com/labstack/echo"
)

const (
	zipcodeTrimLength = 5
)

var (
	instance *controller
	once     sync.Once
)

type controller struct {
	svc   *applicationservice.Service
	cfg   *config.Config
	bcbsi *bcbsi.Service
}

func controllerInstance(svc *applicationservice.Service, cfg *config.Config) *controller {
	once.Do(func() {
		instance = &controller{
			svc:   svc,
			cfg:   cfg,
			bcbsi: bcbsi.New(cfg),
		}
	})
	return instance
}

func (c *controller) handleGetAll(ctx echo.Context) error {
	page, quantity := routeutils.GetPagingParams(ctx)

	list, err := c.svc.Users.GetAll(quantity, page)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	return routeutils.ResponseAPIOK(ctx, list)
}

func (c *controller) handleGetByID(ctx echo.Context) error {
	userID, err := routeutils.GetAndValidateStringParam(ctx, "user_uuid", "mandatory field")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	authUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	item, err := c.svc.Users.GetByUUID(userID, "US")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	rides, err := c.svc.Rides.GetByUserUUID(userID, authUser)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	item.Rides = rides

	return routeutils.ResponseAPIOK(ctx, item)
}

func (c *controller) handlePortalAddress(ctx echo.Context) error {
	userID, err := routeutils.GetAndValidateStringParam(ctx, "user_uuid", "mandatory field")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	item, err := c.svc.Users.GetByUUID(userID, "")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	createdUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	if item.ID == "" {
		return routeutils.ResponseAPIValidationError(ctx, "User not found")
	} else {
		var Address viewmodel.Address
		if err := ctx.Bind(&Address); err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}
		Address.User = item
		Address.CreatedUserUUID = createdUser.ID
		Address, err = c.svc.Users.SaveAddress(Address)
		if err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}

		Address.User, err = c.svc.Users.GetByUUID(userID, "")
		if err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}

		return routeutils.ResponseAPIOK(ctx, Address)
	}
}

func (c *controller) handleRemoveAddress(ctx echo.Context) error {
	addressID, err := routeutils.GetAndValidateStringParam(ctx, "address_uuid", "mandatory field")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	err = c.svc.Users.RemoveAddress(addressID)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	return routeutils.ResponseNoContent(ctx, addressID)
}

func (c *controller) handlePortalContact(ctx echo.Context) error {
	userID, err := routeutils.GetAndValidateStringParam(ctx, "user_uuid", "mandatory field")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	item, err := c.svc.Users.GetByUUID(userID, "")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	createdUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	if item.ID == "" {
		return routeutils.ResponseAPIValidationError(ctx, "User not found")
	} else {
		var Contact viewmodel.Contact
		if err := ctx.Bind(&Contact); err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}
		Contact.User = item
		Contact.Author = createdUser
		Contact, err = c.svc.Users.SaveContact(Contact)
		if err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}

		// Contact.User, err = c.svc.Users.GetByUUID(userID, "")
		// if err != nil {
		// 	return routeutils.HandleAPIError(ctx, err)
		// }

		return routeutils.ResponseAPIOK(ctx, Contact)
	}
}

func (c *controller) handleRemoveContact(ctx echo.Context) error {
	contactUUID, err := routeutils.GetAndValidateStringParam(ctx, "contact_uuid", "mandatory field")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	contact := viewmodel.Contact{
		ID: contactUUID,
	}
	contact, err = c.svc.Users.RemoveContact(contact)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	return routeutils.ResponseNoContent(ctx, contact)
}

func (c *controller) handleMemberAddress(ctx echo.Context) error {
	userID, err := routeutils.GetAndValidateStringParam(ctx, "user_uuid", "mandatory field")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	item, err := c.svc.Users.GetByUUID(userID, "")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	createdUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	if item.ID == "" {
		return routeutils.ResponseAPIValidationError(ctx, "User not found")
	} else {
		var Address viewmodel.Address
		if err := ctx.Bind(&Address); err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}
		Address.User = item
		Address.CreatedUserUUID = createdUser.ID
		Address, err = c.svc.Users.SaveAddress(Address)
		if err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}

		Address.User, err = c.svc.Users.GetByUUID(userID, "US")
		if err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}

		return routeutils.ResponseAPIOK(ctx, Address)
	}
}

func (c *controller) handleMemberDetail(ctx echo.Context) error {
	userID, err := routeutils.GetAndValidateStringParam(ctx, "user_uuid", "mandatory field")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	authUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	item, err := c.svc.Users.GetByUUID(userID, "US")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	rides, err := c.svc.Rides.GetByUserUUID(userID, authUser)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	item.Rides = rides

	if item.ID == "" {
		return routeutils.ResponseAPIValidationError(ctx, "User not found")
	} else {
		return routeutils.ResponseAPIOK(ctx, item)
	}
}

func (c *controller) handlePortalDetail(ctx echo.Context) error {
	userID, err := routeutils.GetAndValidateStringParam(ctx, "user_uuid", "mandatory field")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	item, err := c.svc.Users.GetByUUID(userID, "SP")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	if item.ID == "" {
		return routeutils.ResponseAPIValidationError(ctx, "User not found")
	} else {
		return routeutils.ResponseAPIOK(ctx, item)
	}
}

func (c *controller) stringWithCharset(length int, charset string) string {
	b := make([]byte, length)
	var seededRand *rand.Rand = rand.New(
		rand.NewSource(time.Now().UnixNano()))
	for i := range b {
		b[i] = charset[seededRand.Intn(len(charset))]
	}
	return string(b)
}

func (c *controller) generatePassword(n int) string {
	const (
		charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
	)

	return c.stringWithCharset(n, charset)
}

func (c *controller) handleGetMember(ctx echo.Context) error {
	users, err := c.svc.Users.GetUsersByProfile("US")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	authUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	rides, err := c.svc.Rides.GetAll(authUser)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	for i := range users {
		for _, r := range rides {
			if r.User.ID == users[i].ID {
				users[i].Rides = append(users[i].Rides, r)
			}
		}
	}

	return routeutils.ResponseAPIOK(ctx, users)
}

func (c *controller) handleGetPortal(ctx echo.Context) error {
	users, err := c.svc.Users.GetUsersByProfile("")
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	return routeutils.ResponseAPIOK(ctx, users)
}

func (c *controller) handleMember(ctx echo.Context) error {
	var user viewmodel.User
	if err := ctx.Bind(&user); err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	authUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	if user.PhoneNumber == nil && user.Email == nil || len(*user.PhoneNumber) == 0 && len(*user.Email) == 0 {
		return routeutils.ResponseAPIAuthError(ctx, "phonenumber or email is required", false)
	}

	provider := viewmodel.ProviderResp{}
	user, err = c.svc.Users.CheckAndCreateMember(user, provider, authUser)
	if err != nil {
		if validationError, ok := err.(*viewmodel.ValidationError); ok {
			if len(validationError.Errors) > 0 {
				return routeutils.ResponseAPICustomValidationError(ctx, validationError.Message, validationError.Errors)
			} else {
				return routeutils.ResponseAPIServiceError(ctx, validationError.Message)
			}
		} else {
			return routeutils.HandleAPIError(ctx, err)
		}
	}

	return routeutils.ResponseAPIOK(ctx, user)
}

func (c *controller) handleBulkPortal(ctx echo.Context) error {
	var users []viewmodel.User
	if err := ctx.Bind(&users); err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	authUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	for i, _ := range users {
		if len(users[i].Profiles) == 0 {
			return routeutils.ResponseAPIAuthError(ctx, "profile is required", false)
		}

		if users[i].PhoneNumber == nil || len(*users[i].PhoneNumber) == 0 {
			return routeutils.ResponseAPIAuthError(ctx, "phonenumber is required", false)
		}

		if users[i].Email == nil || len(*users[i].Email) == 0 {
			return routeutils.ResponseAPIAuthError(ctx, "email is required", false)
		}

		if len(users[i].Pass) == 0 {
			return routeutils.ResponseAPIAuthError(ctx, "password is required", false)
		}

		pass, err := b64.StdEncoding.DecodeString(users[i].Pass)
		if err != nil {
			return routeutils.ResponseAPIAuthError(ctx, "Invalid password", false)
		}
		users[i].Pass = string(pass)

		if len(users[i].Name) == 0 && len(users[i].First) == 0 && len(users[i].Last) == 0 {
			return routeutils.ResponseAPIAuthError(ctx, "name is required", false)
		}

		users[i].Test = true
		if len(users[i].First) != 0 && len(users[i].Last) != 0 {
			users[i].Name = fmt.Sprintf("%s %s", users[i].First, users[i].Last)
		}
	}

	returnUser, err := c.svc.Users.CreateBulk(users, authUser)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	return routeutils.ResponseAPIOK(ctx, returnUser)
}

func (c *controller) handlePortal(ctx echo.Context) error {
	var user viewmodel.User
	if err := ctx.Bind(&user); err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	authUser, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	if !authorization.CanCreateUser(authUser, user) {
		return routeutils.ResponseAPIAuthorizationError(ctx)
	}

	if len(user.Profiles) == 0 {
		return routeutils.ResponseAPIAuthError(ctx, "profile is required", false)
	}

	if user.PhoneNumber == nil || len(*user.PhoneNumber) == 0 {
		return routeutils.ResponseAPIAuthError(ctx, "phonenumber is required", false)
	}

	if user.Email == nil || len(*user.Email) == 0 {
		return routeutils.ResponseAPIAuthError(ctx, "email is required", false)
	}

	if len(user.Pass) == 0 {
		return routeutils.ResponseAPIAuthError(ctx, "password is required", false)
	}

	pass, err := b64.StdEncoding.DecodeString(user.Pass)
	if err != nil {
		return routeutils.ResponseAPIAuthError(ctx, "Invalid password", false)
	}
	user.Pass = string(pass)

	if passwordValidationErrors := validation.ValidatePassword(&user); len(passwordValidationErrors) > 0 {
		return routeutils.ResponseAPICustomValidationError(ctx, "Password not strong enough", passwordValidationErrors)
	}

	if len(user.Name) == 0 && len(user.First) == 0 && len(user.Last) == 0 {
		return routeutils.ResponseAPIAuthError(ctx, "name is required", false)
	}

	if len(user.First) != 0 && len(user.Last) != 0 {
		user.Name = fmt.Sprintf("%s %s", user.First, user.Last)
	}
	user.Test = true

	user, err = c.svc.Users.Create(user, authUser)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	return routeutils.ResponseAPIOK(ctx, user)
}

func (c *controller) handleContactType(ctx echo.Context) error {

	cache := cache.Instance(c.cfg)
	cacheKey := ctx.Request().Method + ctx.Request().URL.EscapedPath() + ctx.Request().URL.RawQuery
	resp := []viewmodel.ContactType{}

	err := cache.GetStruct(cacheKey, &resp)

	if err != nil {
		if err != domain.ErrCacheMiss {
			ctx.Logger().Errorf(domain.LogProblemGettingFromCache, err)
		}
		resp, err = c.svc.Users.GetContactType()
		if err != nil {
			return routeutils.HandleAPIError(ctx, err)
		}
		cache.SetStruct(cacheKey, resp)
	}

	return routeutils.ResponseAPIOK(ctx, resp)
}

func (c *controller) handleTokenInfo(ctx echo.Context) error {
	user, err := auth.GetUserDetail(ctx, c.cfg)
	if err != nil {
		return routeutils.HandleAPIError(ctx, err)
	}

	return routeutils.ResponseAPIOK(ctx, user)
}
