import datetime
import json
import requests

from django.contrib.auth.decorators import login_required
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 *
from machine.models import *
from schedule.models import Knit_Process, Warp_Process
from order.models import Order_DesignData
from design_data.models import *

@csrf_exempt
def selectOrder(request):
    orderId = int(request.POST['orderId'])
    desingObj = Order_DesignData.objects.get(pk=orderId).design_data_id.fsty_cad_production.fsty_cad_fabric_set.all()

    print(desingObj[0])

    for obj in desingObj:
        if obj.CAD_Fabric_type == 'R':
            print('qwqwqwqwqwqww')
            infoObj = obj

    twsJsonData = requests.get("http://tnswebserver.iptime.org:1978/values/tws").json()

    trsJsonData = requests.get("http://tnswebserver.iptime.org:1978/values/trs").json()



    print(trsJsonData)

    for obj in twsJsonData['tws']:
        obj['aaaa'] = 'aaaa'

    for obj in trsJsonData['trs']:
        obj['dailyOutPut'] = int(int(obj['trs_rpm_main']) * 24 * 60 / int(infoObj.CAD_Fabric_cpi) / 91.44 * int(infoObj.CAD_Fabric_width))

    machineJsonList = {'tws': twsJsonData['tws'], 'trs': trsJsonData['trs']}

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


@login_required
@csrf_exempt
def showSchedule(request):
    designOrderList = Order_DesignData.objects.filter(warp_process__isnull=True, knit_process__isnull=True).order_by('-id')
    warpMachineList = Warp_Machine.objects.all()
    knitMachineList = Knit_Machine.objects.all()

    return render(request, 'schedule.html', {'title': 'Schedule', 'designOrderList': designOrderList, 'designOrderCount': designOrderList.count(), 'warpMachineList': warpMachineList, 'knitMachineList': knitMachineList})

@csrf_exempt
def getMachineByDate(request):
    year = int(request.POST['year'])
    month = int(request.POST['month'])
    date = int(request.POST['date'])

    endDate = datetime.datetime(year, month, date, 23, 59, 59)
    startDate = datetime.datetime(year, month, date, 0, 0, 0)
    print(endDate)
    print(startDate)

    warpProcessList = Warp_Process.objects.filter(end_time__gte=startDate, end_time__lte=endDate) | Warp_Process.objects.filter(start_time__gte=startDate, start_time__lte=endDate) | Warp_Process.objects.filter(end_time__gt=endDate, start_time__lt=startDate)
    warpProcessJsonList = []
    for warpProcessObj in warpProcessList:
        jsonOrderObj = {}
        jsonOrderObj['order'] = warpProcessObj.order_designdata.code
        jsonOrderObj['warpMachine'] = warpProcessObj.warp_machine_id.tws_code
        jsonOrderObj['startTime'] = warpProcessObj.start_time.strftime("%Y-%m-%d %H:%M")
        jsonOrderObj['endTime'] = warpProcessObj.end_time.strftime("%Y-%m-%d %H:%M")

        warpProcessJsonList.append(jsonOrderObj)

    knitProcessList = Knit_Process.objects.filter(end_time__gte=startDate, end_time__lte=endDate) | Knit_Process.objects.filter(start_time__gte=startDate, start_time__lte=endDate) | Knit_Process.objects.filter(end_time__gt=endDate, start_time__lt=startDate)
    knitProcessJsonList = []
    for knitProcessObj in knitProcessList:
        jsonOrderObj = {}
        jsonOrderObj['order'] = knitProcessObj.order_designdata.code
        jsonOrderObj['knitMachine'] = knitProcessObj.knit_machine_id.trs_code
        jsonOrderObj['startTime'] = knitProcessObj.start_time.strftime("%Y-%m-%d %H:%M")
        jsonOrderObj['endTime'] = knitProcessObj.end_time.strftime("%Y-%m-%d %H:%M")

        knitProcessJsonList.append(jsonOrderObj)

    variable = {'knitProcessList': knitProcessJsonList, 'warpProcessList': warpProcessJsonList}


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

@csrf_exempt
def getMaterialByJson(request):
    type = int(request.POST['type'])

    if type == 1:
        materialList = Yarn.objects.all()
    elif type == 2:
        materialList = Beam.objects.all()
    else:
        materialList = Raw.objects.all()

    return HttpResponse(json.dumps({'materialList': materialList}), content_type='application/json')


@csrf_exempt
def getProcessByJson(request):
    year = int(request.POST['year'])
    month = int(request.POST['month'])
    date = int(request.POST['date'])
    warpMachine = request.POST.get('warpMachine', None)
    knitMachine = request.POST.get('knitMachine', None)

    endDate = datetime.datetime(year, month, date, 23, 59, 59)
    startDate = datetime.datetime(year, month, date, 0, 0, 0)
    print(endDate)
    print(startDate)


    if warpMachine != None:
        warpMachineObj = Warp_Machine.objects.get(pk=warpMachine)
        warpProcessList = Warp_Process.objects.filter(warp_machine_id=warpMachineObj, end_time__gte=startDate, end_time__lte=endDate) | Warp_Process.objects.filter(warp_machine_id=warpMachineObj, start_time__gte=startDate, start_time__lte=endDate) | Warp_Process.objects.filter(warp_machine_id=warpMachineObj, end_time__gt=endDate, start_time__lt=startDate)
        warpProcessJsonList = []
        for warpProcessObj in warpProcessList:
            jsonOrderObj = {}
            jsonOrderObj['order'] = warpProcessObj.order_designdata.code
            jsonOrderObj['startTime'] = warpProcessObj.start_time.strftime("%Y-%m-%d %H:%M")
            jsonOrderObj['endTime'] = warpProcessObj.end_time.strftime("%Y-%m-%d %H:%M")

            warpProcessJsonList.append(jsonOrderObj)

        variable = {'success': True, 'processList': warpProcessJsonList}
    else:
        knitMachineObj = Knit_Machine.objects.get(pk=knitMachine)
        knitProcessList = Knit_Process.objects.filter(knit_machine_id=knitMachineObj, end_time__gte=startDate, end_time__lte=endDate) | Knit_Process.objects.filter(knit_machine_id=knitMachineObj, start_time__gte=startDate, start_time__lte=endDate) | Knit_Process.objects.filter(knit_machine_id=knitMachineObj, end_time__gt=endDate, start_time__lt=startDate)
        knitProcessJsonList = []
        for knitProcessObj in knitProcessList:
            jsonOrderObj = {}
            jsonOrderObj['order'] = knitProcessObj.order_designdata.code
            jsonOrderObj['startTime'] = knitProcessObj.start_time.strftime("%Y-%m-%d %H:%M")
            jsonOrderObj['endTime'] = knitProcessObj.end_time.strftime("%Y-%m-%d %H:%M")

            knitProcessJsonList.append(jsonOrderObj)

        variable = {'success': True, 'processList': knitProcessJsonList}

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

@csrf_exempt
def createSchedule(request):
    orderId = int(request.POST['orderId'])
    warpMachineId = int(request.POST['warpMachineId'])
    warpingStart = request.POST['warpStartTime']
    warpingEnd = request.POST['warpEndTime']
    knitMachineId = int(request.POST['knitMachineId'])
    knitingStart = request.POST['knitStartTime']
    knitingEnd = request.POST['knitEndTime']

    oerder_designObj = Order_DesignData.objects.get(id=orderId)

    warpMachineObj = Warp_Machine.objects.get(id=warpMachineId)
    warpProcessObj = Warp_Process(order_designdata=oerder_designObj, warp_machine_id=warpMachineObj, start_time=warpingStart, end_time=warpingEnd)
    warpProcessObj.save()

    knitMachineObj = Knit_Machine.objects.get(id=knitMachineId)
    knitProcessObj = Knit_Process(order_designdata=oerder_designObj, knit_machine_id=knitMachineObj, start_time=knitingStart, end_time=knitingEnd)
    knitProcessObj.save()

    return redirect('/schedule')
