import base64
import binascii
from random import sample

def encode(password_Str):
	s=""
	for i in password_Str:
		s=s+chr(ord(i)+10)
	return s

def decodePwd(EncodedPwd):
	s=""
	for i in EncodedPwd:
		s=s+chr(ord(i)-10)
	return s

def is_EncodedString_base64(s):
	try:
		# base64.decodestring(s)
		base64.b64decode(s).decode()
		#decodeStr = base64.decodestring(s)
		return True
	except UnicodeDecodeError as e:
		return False
	except binascii.Error:
		return False

def encode_base64(pwdString):
	#password =pwdString.encode('base64','strict')
	password = base64.encodestring(pwdString)
	#password to save in the DB
	return password

def decode_base64(pwdString):
    password = base64.decodestring(pwdString)
    return password # to Read while sending Emails or validations

#If the pwd is already encoded we need to check whether it is encoded or not
#if its encoded while reading we have to decode
#While updating to the DB it has to be encoded and updated in the DB


def pwd_encoding(sample_string):
	sample_string_bytes = sample_string.encode("ascii")
	base64_bytes = base64.b64encode(sample_string_bytes)
	base64_string = base64_bytes.decode("ascii")
	return base64_string

def pwd_decoding(base64_string):
    #print "base64_string",base64_string
	sample_string=" "
	try:
		base64_bytes = base64_string.encode("ascii")
		sample_string_bytes = base64.b64decode(base64_bytes)
		sample_string = sample_string_bytes.decode("ascii")
	except Exception as e:
		sample_string = base64_string
		#print(e)
	return sample_string


def dbSavePwd(password):
	if not is_EncodedString_base64(password):
		en_password = pwd_encoding(password)

	elif password.startswith("hello"):
		en_password = pwd_encoding(password)
		
	elif password.isalnum():
		en_password = pwd_encoding(password)
	else:
		en_password = password

	return en_password

def readDBPwd(password):
	
	if is_EncodedString_base64(password):
		de_password = pwd_decoding(password)

	elif password.startswith("hello"):
		de_password = password
	else:
		de_password = password
	#print de_password

	return de_password
	



#pwd="aGV5aG93YXJleW91"

# if not is_EncodedString_base64(pwd):
# 	pwdEncode = pwd_encoding(pwd)
# 	print pwdEncode

# elif pwd.startswith("hello"):
# 	pwdEncode = pwd_encoding(pwd)
# 	# print "pwd Startswith",pwdEncode

# else:
# 	pwdEncode=pwd

# if is_EncodedString_base64(pwdEncode):
# 	pwdDecode = pwd_decoding(pwdEncode)
# 	print "PWD DECODED",pwdDecode

#print(is_EncodedString_base64("Naveen@123"))
#print(readDBPwd(pwd))

