import json

from django.contrib.auth.decorators import login_required
from django.forms import model_to_dict
from django.http import HttpResponse
from django.shortcuts import render, redirect

# Create your views here.
from django.views.decorators.csrf import csrf_exempt

from materials.models import Yarn, Beam


@login_required(login_url='/')
@csrf_exempt
def showMaterial(request):

    yarnList = Yarn.objects.all()
    beamList = Beam.objects.all()

    return render(request, 'material.html', {'title': 'Materials', 'yarnList': yarnList, 'beamList': beamList})



def createYarn(request):

    name = request.POST['yarnName']
    code = request.POST['yarnCode']
    maker = request.POST['yarnMaker']
    count = request.POST['yarnCount']
    filament = request.POST['yarnFilament']
    contraction = request.POST['yarnContraction']
    material = request.POST['yarnMaterial']
    kind = request.POST['yarnKind']
    color = request.POST['yarnColor']
    qty = request.POST['yarnQty']

    yarn = Yarn(name=name, code=code, maker=maker, count=count, filament=filament, contraction=contraction, material=material, kind=kind, color=color, qty=qty)
    yarn.save()

    return redirect('/material')

def createBeam(request):
    name = request.POST['beamName']
    size = request.POST['beamSize']

    beam = Beam(name = name, size = size)
    beam.save()

    return redirect('/material')


@csrf_exempt
def getYarnInfoByJson(request):
    id = request.POST['id']

    yarn = model_to_dict(Yarn.objects.get(pk=id))

    return HttpResponse(json.dumps(yarn), content_type='application/json')