#from django.shortcuts import render
from django.shortcuts import render, redirect
# Create your views here.
from django.contrib.auth import login, authenticate
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse
from django.contrib.auth.decorators import login_required

from fruit.models import Store, Product, Photo, ProductSKU, Sale, Inbox
from .forms import StoreForm, ProductForm, InboxForm, SaleForm,  PhotoFormSet, InlinePhotoFormset, ProductSKUForm, ProductFilter, SaleFilter, InboxFilter
from django.contrib import messages
from django.core.paginator import Paginator


def index(request):
    return render(request, 'fruit/index.html')



@login_required
def mystore(request):
    stores = request.user.store_created.all().order_by("-created_at")
    products = stores[0].product_set.all().order_by("-created_at")

    if request.method == "POST":
        if 'createStore' in request.POST:
            print("create store")
            name = request.POST.get('name', None)
            store = Store()
            store.name = name
            store.created_by  = request.user
            store.save()

        if 'updateStore' in request.POST:
            print("update store")
            storeForm = StoreForm(request.POST, instance=stores[0])
            if storeForm.is_valid():
                storeForm.save()

        return redirect("fruit:mystore")
            #print("Create Store")
    else:
        storeForm = StoreForm(instance=stores[0])
    #print(dir(request.user))
    return render(request, 'fruit/mystore_index.html', {'stores': stores, 'storeForm': storeForm, 'products': products, 'mystore': True})


@login_required
def product_index(request):
    stores = request.user.store_created.all().order_by("-created_at")
    products = stores[0].product_set.all().order_by("-created_at")

    f = ProductFilter(request.GET, queryset=products)

    paginator = Paginator(f.qs, 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'fruit/product_index.html', {'products': products, 'product': True, 'page_obj': page_obj, 'filter': f})

@login_required
def sale_index(request):
    stores = request.user.store_created.all().order_by("-created_at")
    o_qs = stores[0].sale_set.all().order_by("-created_at")

    f = SaleFilter(request.GET, queryset=o_qs)

    paginator = Paginator(f.qs, 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'fruit/sale_index.html', {'o_qs': o_qs, 'sale_active': True, 'page_obj': page_obj, 'filter': f})

@login_required
def create_product(request):
    stores = request.user.store_created.all().order_by("-created_at")
    form = ProductForm()
    form2 = InlinePhotoFormset()
    if request.method == "POST":
        form = ProductForm(request.POST)
        form2 = InlinePhotoFormset(request.POST, request.FILES)
        if form.is_valid() and form2.is_valid():
            instance1 = form.save(commit=False)
            instance1.created_by = request.user
            instance1.store = stores[0]
            instance1.save()
            instances = form2.save(commit=False)
            print(instances)

            for s in instances:
                s.product = instance1
                s.created_by = request.user
                s.save()
            messages.success(request, "Product Save")

        else:
            if form.errors:
                messages.error(request, form.errors)
            if form2.errors:
                messages.error(request, form2.errors)

            print("Invalid ")
        return redirect("fruit:product_edit", pk=int(instance1.id))

    return render(request, 'fruit/product_form.html', {'product': True, 'form': form, 'form2': form2 })

@login_required
def create_sku(request, pk):
    p = Product.objects.get(pk=pk)
    form = ProductSKUForm(initial={'product':p, 'created_by': request.user})
    if request.method == "POST":
        form = ProductSKUForm(request.POST)
        if form.is_valid():
            i = form.save()
            messages.success(request, "Product Save")
            return redirect("fruit:edit_sku", pk=i.pk)
        else:
            message.error(request, "SKU  created failed")
            return redirect("fruit:create_sku", pk=int(pk))

    return render(request, 'fruit/sku_form.html', {'form': form, 'pid': p.pk})

@login_required
def edit_sku(request, pk):

    p = ProductSKU.objects.get(pk=pk)
    p0 = p.product

    form = ProductSKUForm(instance=p)
    if request.method == "POST":
        form = ProductSKUForm(request.POST)
        if form.is_valid():
            i = form.save()
            messages.success(request, "Product Save")
            return redirect("fruit:edit_sku", pk=i.pk)
        else:
            message.error(request, "SKU  created failed")
            return redirect("fruit:create_sku", pk=int(pk))

    return render(request, 'fruit/sku_form.html', {'form': form, 'pid': p0.pk})

@login_required
def product_edit(request, pk):
    stores = request.user.store_created.all().order_by("-created_at")

    product = Product.objects.get(pk=pk)
    form = ProductForm(instance = product)
    form2 = InlinePhotoFormset(instance = product)

    if request.method == "POST":
        form = ProductForm(request.POST)
        form2 = InlinePhotoFormset(request.POST, request.FILES, instance = product)
        if form.is_valid() and form2.is_valid():
            instance1 = form.save(commit=False)
            instance1.created_by = request.user
            instance1.store = stores[0]
            instance1.save()
            instances = form2.save(commit=True)
            '''
            print(instances)
            for s in instances:
                s.product = instance1
                s.save()
            '''
            messages.success(request, "Product Save")
        else:
            print("Invalid ")
            print(form.errors)
            print(form2.errors)

            if form.errors:
                messages.error(request, form.errors)
            if form2.errors:
                messages.error(request, form2.errors)

        return redirect("fruit:product_edit", pk =  int(pk))

    return render(request, 'fruit/product_form.html', {'product': True, 'form': form, 'form2': form2, 'obj': product })

@login_required
def sale_edit(request, pk):
    stores = request.user.store_created.all().order_by("-created_at")

    obj = Sale.objects.get(pk=pk)
    form = SaleForm(instance = obj)

    if request.method == "POST":
        form = SaleForm(request.POST)
        if form.is_valid():
            instance1 = form.save()
            '''
            print(instances)
            for s in instances:
                s.product = instance1
                s.save()
            '''
            messages.success(request, "Sale Save")
        else:
            print("Invalid ")
            if form.errors:
                messages.error(request, form.errors)

        return redirect("fruit:sale_edit", pk =  int(pk))

    return render(request, 'fruit/sale_form.html', {'sale_active': True, 'form': form, 'object': obj})


@login_required
def inbox_index(request):
    stores = request.user.store_created.all().order_by("-created_at")
    o_qs = stores[0].inbox_set.all().order_by("-created_at")

    f = InboxFilter(request.GET, queryset=o_qs)

    paginator = Paginator(f.qs, 25)
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'fruit/inbox_index.html', {'o_qs': o_qs, 'inbox_active': True, 'page_obj': page_obj, 'filter': f})

@login_required
def inbox_edit(request, pk):
    stores = request.user.store_created.all().order_by("-created_at")

    obj = Inbox.objects.get(pk=pk)
    form = InboxForm(instance = obj)

    if request.method == "POST":
        form = InboxForm(request.POST)
        if form.is_valid():
            instance1 = form.save()
            '''
            print(instances)
            for s in instances:
                s.product = instance1
                s.save()
            '''
            messages.success(request, "Sale Save")
        else:
            print("Invalid ")
            if form.errors:
                messages.error(request, form.errors)

        return redirect("fruit:sale_edit", pk =  int(pk))

    return render(request, 'fruit/inbox_form.html', {'inbox_active': True, 'form': form, 'object': obj})

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('front:index')
    else:
        form = UserCreationForm()
    return render(request, 'fruit/signup.html', {'form': form})
