from django.shortcuts import render

# Create your views here.
def firstPage(req):
    realFloor = showRealFloor(req.POST.get("luckyFloor", "-1"))
    luckyFloor = findFloor(realFloor) or "No value entered yet"
    numbersResult = findNumbers(req.POST.get("numbers", ""))
    recentFloorValue = req.POST.get("luckyFloor", "")
    recentNumValue = req.POST.get("numbers", "")
    password = showSecretMessage(req.POST.get("password", ""))
    isString = checkString(req.POST.get("numbers", ""))
    return render(req, "FirstPage.html", {
        "realFloor": realFloor,
        "luckyFloor": luckyFloor,
        "numbersResult": numbersResult,
        "recentFloorValue": recentFloorValue,
        "recentNumValue": recentNumValue,
        "password": password,
        "isString": isString
    })


def findFloor(floor):
    if not floor:
        return ""
    else:
        count = 0
        for i in range(1, int(floor) + 1):
            count += 1
            while "4" in str(count) or "13" in str(count):
                count += 1
        return count


def showRealFloor(floor):
    if floor == "" or int(floor) < 0:
        return False
    return floor

def checkString(string):
    listStr = []
    for i in string.split():
        if not i.isdigit():
            listStr.append(i)
    #arr = [str(s) for s in string.split() if s.isdigit()]
    if len(listStr) == 1:
        return "one letter"
    elif len(listStr) > 1:
        return True

def findNumbers(nums):
    arr = [int(s) for s in nums.split() if s.isdigit()]
    result = ""
    if nums == "" or len(arr) == 0:
        return False
    else:
        list2 = []
        list3 = []
        count = 1
        for i in range(1, len(arr)):
            if arr[i - 1] == arr[i]:
                count += 1
                string = str(arr[i]) + "x" + str(count)
                list2.append(string)
                if i < len(arr) - 1:
                    if arr[i + 1] != arr[i]:
                        list3.append(list2[-1])
            else:
                if i == 1 and  arr[i - 1] != arr[i]:
                    list3.append(arr[0])
                if i < len(arr) - 1 and arr[i] != arr[i + 1]:
                    list3.append(arr[i])
                list2.append(arr[i])
                count = 1
            if i == len(arr) - 1:
                list3.append(list2[-1])

        if len(arr) == 1:
            result = str(arr[0])
        else:
            result = str(list3[0])
            for i in range(1, len(list3)):
                result += ", " + str(list3[i])
    return result

def showSecretMessage(password):
    if password == "time":
        return True
    elif password == "":
        return ""
    return False
