#!/usr/bin/env python

import re

# create the MyNavBar.qml
# this avoids having to create it dynamically

def createNavBarQmlObjectFile(navBarItems,paramJson,paramLayoutVersion,page2nav,force=False):

        s = """
import QtQuick 2.9
import QtQuick.Controls 1.5
import QtQuick.Controls.Styles 1.4
import QtQml.Models 2.2

// py auto-generated navigation pane and parameter objects 
// the navBar also holds the lists of the parameter objects
// LayoutVersion: L"""+str(paramLayoutVersion)+"""

Column {
    //id: navBar
       
    property string currentNavIndexStr: '"""
        s += "Dashboard" + """'
    
    //list of nav pages in the nav bar    
    readonly property var navBarItems: [
"""
#         { nav: 'DashBoard', icon: '../icons/ic_menu_black_48dp.png'},
        for item in navBarItems:
            icon = 's.iconNavbar' + item['nav'].replace(' ','')
            s += "        { nav: '" + item['nav'] + "', icon: " + icon + " },\n"
        s += """    ]

    //int constants for indexing the nav pages 
"""
#    readonly property int iDashBoard: 0
        i = 0
        for item in navBarItems:
            s += "    readonly property int i" + item['nav'].replace(' ','') + ": " + str(i) + "\n"
            i += 1
        s += """
    //create the MyNavButton objects in the nav bar    
    Repeater {
        model: parent.navBarItems
        MyNavButton {
            text: modelData.nav
            iconSource: modelData.icon
            navIndexStr: modelData.nav //index
        }
    }

    //list of all parameters, and associated meta data 
    readonly property var paramItems: [
"""    
#        { name: 'Name', type: 'STR', adr: 1, nav: 'DashBoard' },
        
        #this we need later
        # we can get cCMD_g_PARAMETER_ZAHL from the SCRIPT adr+1
        # we can get cSCRIPTSIZE from the size of SCRIPT
        cCMD_g_PARAMETER_ZAHL = 0
        cSCRIPTSIZE = 0

        for item in paramJson:
            if not item['page'] in page2nav:
                print( item['page'], " is not in page2nav")
                continue
            s += "        { "
            s += "name: '"      + item['name']          + "', "
            s += "nav: '"       + page2nav[item['page']] + "', "
            #type can be
            # 'STR+READONLY', 'LIST', 'UINT', 'INT', 'SCRIPT'
            type = item['type']  #''
            if item['type'] == 'STR+READONLY':
                pass; #type = 'STR+READONLY'
            elif item['type'] == 'LIST':
                pass; #type = 'LIST'
            elif item['type'] == 'UINT':
                pass; #type = 'UINT'
            elif item['type'] == 'INT':
                pass; #type = 'INT'
            elif item['type'] == 'SCRIPT':
                pass; #type = 'SCRIPT'
            else:
                print('type unknown:', item['type'] )
                
            s += "type: '"      + type                  + "', "
            s += "size: "       + str(item['size'])     + ", "
            s += "foc: "        + str(item['foc'])      + ", "
            s += "hidden: "     + str(item['hidden'])   + ", "
            
            if type == 'STR+READONLY':
                s += "adr: "     + str(-1)              + ", "
                s += "default: " + "''"                 + ", "
                #s += "steps: "   + str(item['steps'])   + ", "
                #s += "unit: '"   + item['unit']         + "', "
            
            elif type == 'LIST':
                s += "adr: "     + str(item['adr'])     + ", "
                s += "default: " + str(item['default']) + ", "
                #s += "steps: "   + str(item['steps'])   + ", "
                #s += "len: "     + str(item['len'])     + ", "
                #s += "ppos: "    + str(item['ppos'])    + ", "
                s += "min: "     + str(item['min'])     + ", "
                s += "max: "     + str(item['max'])     + ", "
                #s += "unit: '"   + ""                   + "', "
                c = ""
                for choice in item['choices']:
#                    c += "'" + str(choice) + "',"
                    c += "'" + choice + "'," #possible integer choices are converted to string in PySTorM32_createParamJsons.py
                s += "choices: [" + c[:-1] + "], "
                
            elif (type == 'UINT') or (type == 'INT'):
                s += "adr: "     + str(item['adr'])     + ", "
                s += "default: " + str(item['default']) + ", "
                s += "steps: "   + str(item['steps'])   + ", "
                s += "len: "     + str(item['len'])     + ", "
                s += "ppos: "    + str(item['ppos'])    + ", "
                s += "min: "     + str(item['min'])     + ", "
                s += "max: "     + str(item['max'])     + ", "
                s += "unit: '"   + item['unit']         + "', "
                
            elif type == 'SCRIPT':
                s += "adr: "     + str(item['adr'])     + ", "
                s += "default: " + str(0)               + ", "
                s += "steps: "   + str(item['steps'])   + ", "
                s += "len: "     + str(item['len'])     + ", "
                s += "ppos: "    + str(item['ppos'])    + ", "
                s += "min: "     + str(item['min'])     + ", "
                s += "max: "     + str(item['max'])     + ", "
                #s += "unit: '"   + item['unit']         + "', "
                
                cCMD_g_PARAMETER_ZAHL = item['adr'] + 1
                cSCRIPTSIZE = item['size']

            s = s[:-2] + " },\n"
        s += """    ]
        
    // every entry in paramItems MUST have an adr (adr<0 indicates that it's not in read/write)
    // but not every adr must have an entry in paramItems
    // every entry with adr>=0 must be int type, inclusive SCRIPT 
    
    // in contrast to paramItems, this list is arranged by adr
    // it mirrors the 'g' and 'p' simple serial commands, exclusive SCRIPT
    // fill it with enough vaues, so that we have a contiguous array
    // it could be longer, but ideally it would have the correct size

"""
        s += "    readonly property int cCMD_g_PARAMETER_ZAHL: " + str(cCMD_g_PARAMETER_ZAHL) + "\n"
        s += "    readonly property int cSCRIPTSIZE: " + str(cSCRIPTSIZE) + "\n"
        s += "\n"
        s += "    property var paramValues: [\n"

        s += "        "
        for i in range(cCMD_g_PARAMETER_ZAHL):
            s += "0,"
            if i%5 == 4: s += " "
            if i%20 == 19: s += "\n        "
        s += "\n" + "        //scripts" + "\n        "
        for i in range(cSCRIPTSIZE):
            s += "0,"
            if i%5 == 4: s += " "
            if i%20 == 19: s += "\n        "
        s += "\n"

        s += """    ]
    
    //list of MyParamItem objects, arranged by their nav page    
    property list<ObjectModel> paramList: [
"""
        for navItem in navBarItems:
            s += "        ObjectModel {\n"
            i = 0
            for item in paramJson:
#                if (navItem['nav'] == page2nav[item['page']]) and (item['type'] != 'OPTTYPE_SCRIPT'):
#                    s += "            MyParamItem{ paramItem: paramItems[" + str(i) + "] }\n"
                if (navItem['nav'] == page2nav[item['page']]):
                    #id = item['name'].replace(' ','').replace('#','').replace('-','')
                    #id = id.replace('(0=','').replace('(','').replace(')','')
                    #regex = re.compile(r'\(.*\)$')
                    #id = regex.sub('', id)
                    #id = "id: p" + id
                    
                    pIndex = "paramIndex: " + str(i)
                    
                    pItem = "paramItem: paramItems[" + str(i) + "]"
                
                    if item['type'] == 'STR+READONLY':
                        s += "            MyParamItemStrReadOnly{ " + pIndex + "; " + pItem + " }\n"
                    elif item['type'] == 'LIST':
                        s += "            MyParamItemList{ " + pIndex + "; " + pItem + " }\n"
                    elif item['type'] == 'UINT':
                        s += "            MyParamItemInt{ " + pIndex + "; " + pItem + " }\n"
                    elif item['type'] == 'INT':
                        s += "            MyParamItemInt{ " + pIndex + "; " + pItem + " }\n"
                    elif item['type'] == 'SCRIPT':
                        s += "            MyParamItemScript{ " + pIndex + "; " + pItem + " }\n"
                        s += "            MyScriptTextArea{ id: scriptTextArea1; label: 'Script1' }\n"
                        s += "            MyScriptTextArea{ id: scriptTextArea2; label: 'Script2' }\n"
                        s += "            MyScriptTextArea{ id: scriptTextArea3; label: 'Script3' }\n"
                        s += "            MyScriptTextArea{ id: scriptTextArea4; label: 'Script4' }\n"
                       
                i += 1
            s += "        },\n"
        s = s[:-2] + """
    ]    
}
"""
        createMyNavBarQml = False
        try: F = open( 'resources/controls/MyNavBar.qmlc', 'r')
        except IOError: createMyNavBarQml = True
        else: pass #such a file is existing, so don't do anything

        if createMyNavBarQml or force:
            F = open( 'resources/controls/MyNavBar.qml', 'w', encoding = "utf-8") #the encoding is important to get '°' correct
            F.write( s )
            F.close()
            print( 'MyNavBar.qml created')
