#!/usr/bin/env python3 
#coding=utf-8
import sys
import os, re
import importlib




separ = "//----------------------------------------------------------------------------------- "

pnzv = os.popen("git status| head -n1 |cut -d \" \" -f 3").read().strip()

if len(pnzv) > 0:
	model = str(pnzv)
else:
	print "chyba zpracovani git status"
	exit()


rezim = 0

if len(sys.argv) > 1:
  if sys.argv[1] not in ("bin", "txt", "define", "all"):
    print "chyba vstupni parametr [bin, txt, define, all]"
  else:
    tajp = sys.argv[1]
    if tajp == "bin":
      rezim = 1
    if tajp == "define":
      rezim = 2
    if tajp == "txt":
      rezim = 3
    if tajp == "all":
      rezim = 0

suffix = ""
if len(sys.argv) > 2:
  suffix = sys.argv[2]

if suffix == "a1z2":
  suffix = ""

deska = ""
if len(sys.argv) > 3:
  deska = sys.argv[3]

if len(deska) < 1:
  print "Neni dustupna definice desky"
  exit()

sys.path.insert(0, './' + deska)
from data import *

sumStruct = sum(STRUCTsize)

model = deska + "-" + pnzv

  
souborModelC = deska + "/model.c"
souborModelH = deska + "/model.h"
souborDefine = deska + "/define.h"
#souborBin = "bin/" + model + "-" + str(suffix) + ".bin"
#souborTxt = "bin/" + model + "-" + str(suffix) + ".txt"

souborBin = deska + "/" + model + "-" + str(suffix) + ".bin"
souborTxt = deska + "/" + model + "-" + str(suffix) + ".txt"



if rezim in (0, 1):
  f = open(souborBin, 'wb')

velikost = 640
startPam = 0x4000
endPam = 0x4280
pocitadlo = 0

def zpracuj2byte(cislo):
  b1 = cislo >> 8
  b2 = cislo & 0x00FF
  rar = [b1, b2]
  
  return bytearray(rar)
  
# sestaveni popisu a kontrola poctu hodnot
definiceT = ""
popis = ""
popisPole = []
poziceTxt = 0
indexStruct = 0

if len(valEEP8) != STRUCTsize[0]:
	print "Nesedi pocet 8bit hodnot"
	os.system("rm define.h")
	exit(1)

if len(valEEP16) != sum(STRUCTsize[1:-2]):
	print "Nesedi pocet 16bit hodnot"
	os.system("rm define.h")
	exit(1)
	
if len(valEEPpid16) != sum(STRUCTsize[-2:]):
	print "Nesedi pocet pid hodnot"
	os.system("rm define.h")
	exit(1)
	
polehodnot = valEEP8 + valEEP16 + valEEPpid16

for stu in STRUCTsize:
	popis += str(indexStruct + 1)
	for it in range(poziceTxt, poziceTxt + STRUCTsize[indexStruct]):
		popisPole.append(str(textEEP[it]) + " " + str(polehodnot[it]))
	popis += "".join(popisPole)
	popis += "\n"
	popisPole = []
	poziceTxt = poziceTxt + STRUCTsize[indexStruct]
	indexStruct += 1

definiceT += separ + "\n"
definiceT += "#define EEPstart        " + hex(startPam) + "\n"
definiceT += "#define EEPend          " + hex(endPam) + "\n"
definiceT += separ

# zapis 8bit #
if rezim in (0, 1):
  f.write(bytearray(valEEP8))


definiceD = ""  
pocitadlo += len(valEEP8)
definiceT += "\n#define EEPsystem8      " + hex(startPam) + " // system8"

#zapis jednotlive texty
cnt = 0
for cislo in valEEP8:
  definiceD += ("\n#define EEP_" + textDefine[cnt]).ljust(25, ' ')  + hex(startPam + cnt) + ""
  cnt += 1

definiceT += "\n#define EEPsystem16     " + hex(startPam + pocitadlo) + " // system16"

#zapis jednotlive texty16
dbl = 0
for cislo in valEEP16:
  definiceD += ("\n#define EEP_" + textDefine[cnt]).ljust(25, ' ') + hex(startPam + pocitadlo + dbl) + ""
  cnt += 1
  dbl += 2

# zapis 16bit #
if rezim in (0, 1):
  for cislo in valEEP16:
    #print cislo, cislo >> 8, cislo & 0x00FF
    f.write(zpracuj2byte(cislo))
pocitadlo += len(valEEP16) * 2 

definiceT += "\n#define EEPpid          " + hex(startPam + pocitadlo) + " // pid"

#zapis jednotlive textypid16
dbl = 0
for cislo in valEEPpid16:
  definiceD += ("\n#define EEP_" + textDefine[cnt]).ljust(25, ' ') + hex(startPam + pocitadlo + dbl) + ""
  cnt += 1
  dbl += 2

if rezim in (0, 1):
  for cislo in valEEPpid16:
    f.write(zpracuj2byte(cislo))
pocitadlo += len(valEEPpid16) * 2
definiceT += "\n#define EEPtext         " + hex(startPam + pocitadlo) + " // text"
definiceT += "\n" + separ

definiceT += definiceD + "\n" + separ

definice = ["#define textWatchdog    ",
            "#define textStart       ",
            "#define textStop        ",
            "#define textBreak       ",
            "#define textLoad        ",
            "#define textReset       ",
            "#define textSave        ",
            "#define textERASE       ",
            "#define textIz          ",
            "#define textUn          ",
            "#define textUr          ",
            "#define textPSdec       ",
            "#define textTLmRezim    ",
            "#define textTLpUlozit   ",
            "#define textTEST        ",
            "#define textRucne       ",
            "#define textSinus       ",
            "#define textUfix        ",
            "#define textMPPT        "]

portxt = 0
pocTexty = 0  
for text in textEEP:
  #print cislo, cislo >> 8, cislo & 0x00FF
  if pocTexty > sumStruct - 1 and text != "\0":
    definiceT += "\n" + definice[portxt] + hex(startPam + pocitadlo) + " // " + (textEEP[sumStruct + portxt]).replace('\n', '')
    portxt += 1
  if rezim in (0, 1):
    f.write(bytearray(text))
    f.write(bytearray("\0"))
  pocitadlo += len(text) + 1
  pocTexty += 1

definiceT += "\n"

#define EEPstruct       8      
modelH = separ + "\n"
modelH += "#define EEPstruct       " + str(len(STRUCTsize)) + "      // počet seznamů dat v EEPROM " + "\n"
modelH += separ + "\n"

modelC  = separ
modelC += "\n#define MODEL           \"" + model + "\"\n"
modelC += separ + "\n"
modelC += "const uint8_t  STRUCTsize[EEPstruct] = {" + ", ".join(str(x) for x in STRUCTsize) + "}; // počet hodnot ve strukturách v EEPROM" + "\n"
modelC += separ + "\n"

#definiceT  += "// const uint8_t  STRUCTsize[EEPstruct] = {" + ", ".join(str(x) for x in STRUCTsize) + "}; // počet hodnot ve strukturách v EEPROM\n" + separ 
#definiceTxt = "// const uint8_t  STRUCTsize[EEPstruct] = {" + ", ".join(str(x) for x in STRUCTsize) + "}; // počet hodnot ve strukturách v EEPROM\n" + separ 

nuly = []
for i in range(pocitadlo, (velikost - 32)):
  nuly.append(0)
pocitadlo += len(nuly)

if rezim in (0, 1):
  f.write(bytearray(nuly))

definiceTxt  = model + "\n" + popis
definiceTxt += "eeprom free " + str(len(nuly))
popis += "eeprom free " + str(len(nuly))

if (len(model) + 3) > 32:
  print model, "chyba model len > \n\n + 29 + \0"
else:
  if rezim in (0, 1):
    f.write(bytearray("\n"))
    f.write(bytearray("\n"))
    f.write(bytearray(model))
    f.write(bytearray("\0"))
    pocitadlo += len(model) + 3

nuly = []
for i in range(pocitadlo, velikost):
  nuly.append(0)

if rezim in (0, 1):  
  f.write(bytearray(nuly))

#1 eeprom.bin
if rezim in (0, 1):
  f.close()
  print "create", souborBin

#2 define.h
if rezim in (0, 2):
  with open(souborModelC, "w") as myfile:
    myfile.write(modelC)
  print "create", souborModelC
  with open(souborModelH, "w") as myfile:
    myfile.write(modelH)
  print "create", souborModelH
  with open(souborDefine, "w") as myfile:
    myfile.write(definiceT)
  print "create", souborDefine

#3 eeprom.txt
if rezim in (0, 3):
  with open(souborTxt, "w") as myfile:
    myfile.write(definiceTxt)
  print "print ", souborTxt, "\n", popis

