# -*- coding: utf-8 -*-

import sys, getopt
import time
import random
import argparse


soubor = "soubor_gpio.txt"
running = 1


def file_write_default():
    open(soubor, "w").close()
    file = open(soubor, "r+")
    file.write("0\n" + "0\n" + "0\n" + "0\n" + "0\n" + "0\n" + "0\n" + "0\n")
    file.close()

def readfile():
    rfile = open(soubor, "r")
    lines = rfile.readlines()
    rfile.close()
    return lines

"""
def intToStr(intData):
    strData = ""
    for z in range(len(intData)):
        strData += str(intData[z]) + "\n"
    return strData
"""

def writefile():
    wfile = open(soubor, "r+")
    data = random_data(readfile())
    #print("Random lines " + str(data))
    wfile.writelines(data)
    print("Data are\n" + str(data))
    print("----------------------")
    wfile.close()

def wfOnlyGPIO():
    wfile = open(soubor, "r+")
    inputGPIOdata = readfile()
    data = random_data(inputGPIOdata[4:])
    wfile.writelines(inputGPIOdata[4:] + data[:4])
    print("Data are\n" + str(inputGPIOdata[4:] + data[:4]))
    print("----------------------")
    wfile.close()

def random_data(d):
    for i in range(len(d)):
        d[i] = str(random.randint(0, 1)) + "\n"
    return d

def random_sleep(l, h):
    min = num(l)
    max = num(h)
    return random.randint(min, max)

def num(s):
    try:
        return int(s)
    except ValueError:
        return float(s)

def switch(x):
    return {
      'a': 1,
      'b': 2
     }.get(x, 9)



if __name__ == "__main__":
    file_write_default()

    parser = argparse.ArgumentParser()

    parser.add_argument("min", type=int,
                        help="Min sleep time")

    parser.add_argument("max", type=int,
                        help="Max sleep time")

    parser.add_argument("-v", "--verbose", action="store_true",
                        help="increase output verbosity")

    parser.add_argument("-i", "--onlyInputGPIO", action="store_true",
                        help="Random only input GPIO - 26,27,28,29")

    parser.add_argument("-a", "--allGPIO", action="store_true",
                        help="Random all GPIO")
    args = parser.parse_args()


    while running:

        random_time = random_sleep(args.min, args.max)

        if args.allGPIO & args.onlyInputGPIO:
            print("You can't have everything. Random all GPIO.")
            writefile()

        elif args.verbose & args.onlyInputGPIO:
            print("Random only input GPIO.\nRandom time is {} sec.".format(random_time))
            wfOnlyGPIO()

        elif args.allGPIO & args.verbose:
            print("Random all GPIO.\nRandom time is {} sec.".format(random_time))
            writefile()

        elif args.onlyInputGPIO:
            wfOnlyGPIO()

        elif args.allGPIO:
            writefile()

        else:
            print("No arguments. Random all GPIO.")
            writefile()


        time.sleep(random_time)
