In [ ]:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.contrib.auth import authenticate, login, logout
from django.contrib import messages
from django.http import *
from django.shortcuts import render_to_response,redirect
from django.template import RequestContext
from django.contrib.auth.decorators import login_required
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserChangeForm
from django.db.models import Q
from django.db.models import Count
from datetime import datetime
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth import update_session_auth_hash
from django.contrib.auth.forms import PasswordChangeForm
from datetime import date
from .models import tasksx
from .models import courses
from udemy import *
import pandas as pd
import json
from pandas.io.json import json_normalize
from django.db.models import Sum

def change_password(request):
    if request.method == 'POST':
        form = PasswordChangeForm(request.user, request.POST)
        if form.is_valid():
            user = form.save()
            update_session_auth_hash(request, user)  # Important!
            messages.success(request, 'Your password was successfully updated!')
            return redirect('change_password')
        else:
            messages.error(request, 'Please correct the error below.')
    else:
        form = PasswordChangeForm(request.user)
    return render(request, 'change_password.html', {
        'form': form
    })


def index(request):
    skill_list = tasksx.objects.filter(creator=request.user).order_by('current')
    course_list = courses.objects.filter(creator=request.user)
    current_total = tasksx.objects.filter(creator=request.user).aggregate(Sum('current'))
    starting_total = tasksx.objects.filter(creator=request.user).aggregate(Sum('starting'))
    count = tasksx.objects.filter(creator=request.user).count()
    try:
        delta = current_total['current__sum']- starting_total['starting__sum']
    except:
        delta = '0'
    context = {'count' : count, 'skill_list' : skill_list, 'course_list' : course_list, 'starting_total' : starting_total['starting__sum'], 'current_total' : current_total['current__sum'], 'delta' : delta}
 
    return render(request, 'index.html', context)


def logout_user(request):
    logout(request)
    return redirect('login')

def login_user(request):
    if request.method == 'POST':
        user = request.POST.get('username').lower()
        password = request.POST.get('password')
        user = authenticate(username=user, password=password)
        if user is not None:
            login(request, user)
            return redirect('index')
        else:
            messages.success(request, ('Login failed'))
            return redirect('login')
    else:
        return render(request, 'login.html', {})

def logout_user(request):
    logout(request)
    return redirect('login')

def signup(request):
    if request.method == 'POST':
        form = UserCreationForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=username, password=raw_password)
            login(request, user)
            return redirect('index')
    else:
        form = UserCreationForm()
    return render(request, 'signup.html', {'form': form})


def create_task(request):
    if request.method == 'POST':
        creator = request.user
        job_title = 'data engineer'
        skill_name = request.POST.get('skill_name')
        starting = request.POST.get('starting')
        description = request.POST.get('description')
        target_date = request.POST.get('target_date')

        if tasksx.objects.filter(skill_name='skill_name', creator=request.user).exists() is True:
            messages.success(request, ('Skill Is A Duplicate  '))
            return redirect('index')

        else:
            i = tasksx.objects.create(target_date2=target_date, creator=creator, job_title=job_title, skill_name=skill_name,  starting=starting, current=starting, description=description)
        
            try:
                if  starting != '100':
                    Client = PyUdemy(clientID = 'clientid', clientSecret = 'clientsecret')

                    response = Client.get_courseslist(search = skill_name, ordering='highest-rated')
                    data = json.loads(response)
                    df1 = json_normalize(data['results'])
                    chosen_course = df1.iloc[0]
                    chosen_coursex = pd.DataFrame(chosen_course).T
            
                    creator = request.user
                    chosen_title = chosen_coursex.iloc[0]['title']
                    chosen_price = chosen_coursex.iloc[0]['price']
                    chosen_img = chosen_coursex.iloc[0]['image_240x135']
                    chosen_url = chosen_coursex.iloc[0]['url']
                    chosen_url = 'https://udemy.com' + chosen_url
        
                    j = courses.objects.create(creator=creator, course_title=chosen_title, chosen_price=chosen_price, chosen_img=chosen_img, chosen_url=chosen_url, skill=skill_name)
            except:
                print('error')
            messages.success(request, ('Skill created  '))
            return redirect('index')

def skill_delete(request):
    t = tasksx.objects.get(id=request.POST.get('deletebutton'))
    skill_name = t.skill_name
    
    t.delete() # this will update only
    
    try:
        y = courses.objects.get(skill=skill_name, creator=request.user)
        y.delete()
    except:
        print('error')

    messages.success(request, ('You have deleted a skill  ' + skill_name))
    return redirect('index')

def edit_skill(request):
    t = tasksx.objects.get(id=request.POST.get('editbutton'))
    
    t.current = request.POST.get('starting')
    t.description = request.POST.get('description')
    if  request.POST.get('starting') == '100':
        try:
            y = courses.objects.get(skill=t.skill_name, creator=request.user)
            y.delete()
        except:
            print('error')

    t.save() # this will update only
    messages.success(request, ('Changes saved'))
    
    return redirect('index')