import os
import CloudConnector
import staas.settings as settings
from django.shortcuts import render, get_object_or_404
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import HttpResponseRedirect
from .forms import SignUpForm
from .models import Uploads, Account, Notification, Folders, Access
from datetime import datetime

#-------------- Helper Functions ----------------#
def get_realnames(uploads):
	real_names = []
	for up in uploads:
		real_names.append(up.upload_file.name.split('/')[-1])
	return real_names

def redirect_to_login(request):
	return HttpResponseRedirect('/login/')

def disk_usage(path):
	total = os.path.getsize(path)
	if os.path.isdir(path):
		for f in os.listdir(path):
			child_path = os.path.join(path,f)
			total = total + disk_usage(child_path)
	return total

#------------ Main Page ----------------------#
@login_required(login_url='/login/')
def index(request,folder_slug):
	cur_folder = ''
	prev_page = '/cloud'
	if folder_slug:
		folders = folder_slug.split('/')
		for f in folders:
			if f:
				prev_page += cur_folder+"/"
				cur_folder = f
	
	user = request.user.id

	dir_in = Folders.objects.filter(folder_name=cur_folder)
	if dir_in:
		dir_in = dir_in[0]
	else:
		return render(request,'404.html')

	current_folder_uploads = Uploads.objects.filter(user=User.objects.filter(id=user),
		dir_in=dir_in)
	current_folder_foldernames = Folders.objects.filter(user=User.objects.filter(id=user),
		dir_in=dir_in)
	shared = Access.objects.filter(user=request.user.username)

	shared_files = []
	for s in shared:
		_file = Uploads.objects.filter(upload_file=s.filename)
		if _file:
			shared_files.append(_file[0])

	folder_sizes = []
	for f in current_folder_foldernames:
		f_size = disk_usage('{0}/media/user_{1}/{2}'.format(settings.BASE_DIR, user, f.folder_name))
		folder_sizes.append(f_size)

	real_names = get_realnames(current_folder_uploads)
	share_names = get_realnames(shared_files)
	
	zip_uploads = zip(current_folder_uploads, real_names)
	zip_folders = zip(current_folder_foldernames, folder_sizes)
	zip_shared = zip(shared_files, share_names)

	return render(request, 'cloud/index.html',
		{'uploads': zip_uploads, 'folders': zip_folders,
		'shares': zip_shared,
		'prev_page': prev_page})

#---------------- Create Folder ---------------------#
@login_required(login_url='/login/')
def create_folder(request, folder_slug):
	user_id = 'user_{}/'.format(request.user.id)
	cur_folder=''
	if folder_slug:
		folders = folder_slug.split('/')
		for f in folders:
			if f:
				cur_folder = f

	user = request.user.id
	if request.method == 'POST':
		dir_in = Folders.objects.filter(folder_name=cur_folder)
		if dir_in:
			dir_in = dir_in[0]
		else:
			return render(request,'404.html')

		folder = Folders()

		folder.user = User.objects.filter(id=user)[0]
		folder.folder_name = request.POST['fname']
		folder.dir_in = dir_in

		try:
			folder.save()
		
			folder_name = folder_slug + '/' + request.POST['fname']
			os.mkdir(settings.MEDIA_ROOT +'/'+ user_id + folder_name)

			messages.success(request, 'Folder Created Successfully!')
		except Exception as e:
			messages.warning(request, 'Sorry! There was a problem. Please Try Again.')
	else:
		messages.warning(request, 'Bad Request!')

	if folder_slug:
		folder_slug += '/' 
	return HttpResponseRedirect('/cloud/{}'.format(folder_slug))


#----------------- Upload File ------------------------#
@login_required(login_url='/login/')
def upload(request, folder_slug):
	cur_folder=''
	if folder_slug:
		folders = folder_slug.split('/')
		for f in folders:
			if f:
				cur_folder = f

	user = request.user.id
	if request.method=='POST' and request.FILES['upload_file']:
		dir_in = Folders.objects.filter(folder_name=cur_folder)
		if dir_in:
			dir_in = dir_in[0]
		else:
			return render(request,'404.html')

		_file = request.FILES['upload_file']

		_dir_in = folder_slug.replace('/', '!@#$%')

		upload = Uploads()
		upload.user = User.objects.filter(id=user)[0]

		'''
		TODO: Check file name
		'''

		_file.name = "{1}!@#$%{0}".format(_file.name, _dir_in)
		upload.upload_file = _file
		upload.dir_in = dir_in
		
		try:
			upload.save()
			messages.success(request, 'Uploaded Successfully!')
		except Exception:
			messages.warning(request, 'Sorry! There was a problem. Please Try Again.')
	else:
		messages.warning(request, 'Bad Request!')

	if folder_slug:
		folder_slug += '/' 
	return HttpResponseRedirect('/cloud/{}'.format(folder_slug))

#--------------- Delete File ------------------------#
def delete_file(request, file_name):
	try:
		user_id = 'user_{0}'.format(request.user.id)
		Uploads.objects.filter(upload_file=user_id+'/'+file_name).delete()
		os.remove(settings.MEDIA_ROOT +'/'+ user_id+'/'+file_name)
		messages.success(request, 'Successfully Deleted!')

	except Exception:
		messages.warning(request, 'Bad request')

	return HttpResponseRedirect(request.GET.get('next', ''))
		
#------------ Delete Folder -------------------------#
def delete_folder(request, folder_slug):
	folder_name = folder_slug.split('/')[-1]

	try:
		user = request.user.id
		
		Folders.objects.filter(folder_name=folder_name).delete()
		
		os.rmdir(settings.MEDIA_ROOT +'/user_'+ str(user) +'/'+folder_name)
		messages.success(request, 'Successfully Deleted!')

	except Exception:
		messages.warning(request, 'Bad request')

	return HttpResponseRedirect(request.GET.get('next', ''))

#------------- Share ------------------#
@login_required(login_url='/login/')
def share(request, file_name):
	user = request.user.id
	
	if request.method=="POST":
		user_name = request.POST['uname']
		u = User.objects.filter(username=user_name)
		
		file_name = 'user_{0}/{1}'.format(user, file_name)

		if u:
			access = Access(filename=file_name, user=user_name)
			try:
				access.save()
				messages.success(request, 'Successfully Shared')
			except Exception:
				messages.warning(request, 'Unable to Share')
		else:
			messages.warning(request, 'User not found')
	else:
		messages.warning(request, 'Bad request')

	return HttpResponseRedirect(request.GET.get('next', ''))

#------------- Sign Up -----------------------------#
def signup(request):
	if request.method=="POST":
		uname = request.POST['username']
		passw = request.POST['password']
		fname = request.POST['first_name']
		lname = request.POST['last_name']

		u = User()
		u.username = uname
		u.set_password(passw)
		u.first_name = fname
		u.last_name = lname
		
		try:
			u.save()
			
			acc = Account()
			acc.user = u
			acc.subscription_type = 'free'		
			acc.save()

			f = Folders(user=u, folder_name='')
			f.save()

			cloud_connector = CloudConnector.CloudConnector(u.id)
			if cloud_connector:
				out = cloud_connector.create_lvm()
				if out==1:
					out = cloud_connector.mount_lvm()
					if out!=1:
						raise Exception
				else:
					raise Exception
			
		except Exception:
			cloud_connector = CloudConnector.CloudConnector(u.id)
			if cloud_connector:
                        	cloud_connector.revert()

			u.delete()
			
			messages.warning(request, 'Sorry! There was a problem signing you up. Please Try Again.')
			return HttpResponseRedirect('/login/')

		messages.success(request,'Signed Up Successfully')
		return HttpResponseRedirect('/login/')
	else:
		users = User.objects.all().values('username')
		signupform = SignUpForm()

	return render(request, 'cloud/signup.html', {'signupform': signupform, 'usernames': users})
