Beispiel #1
0
    def Test_get_legend_steps(self):

        legend_steps = querydb.get_legend_steps(legendid=6)
        logger.info("Legend info: %s", legend_steps)
        for row in legend_steps:
            color_rgb = row.color_rgb
            print color_rgb.split(' ')

        self.assertEqual(1, 1)
Beispiel #2
0
    def Test_get_legend_steps(self):

        legend_steps = querydb.get_legend_steps(legendid=6)
        logger.info("Legend info: %s", legend_steps)
        for row in legend_steps:
            color_rgb = row['color_rgb']
            print color_rgb.split(' ')

        self.assertEqual(1, 1)
def generateLegendHTML(legend_id):
    legendHTMLHorizontal = ''
    legendHTMLVertical = ''
    legendName = ''
    TotSteps = 0
    TotColorLabels = 0
    TotGroupLabels = 0
    legends_HTML = {'legendHTML': '', 'legendHTMLVertical': ''}

    if legend_id == None:
        return legends_HTML

    # print ('legend_id: ' + str(legend_id))
    legend_info = querydb.get_legend_info(legendid=legend_id)
    if hasattr(legend_info, "__len__") and legend_info.__len__() < 1:
        return legends_HTML

    legend_steps = querydb.get_legend_steps(legendid=legend_id)
    if hasattr(legend_steps, "__len__") and legend_steps.__len__() < 1:
        return legends_HTML

    getTotSteps = querydb.get_legend_totals(legendid=legend_id)
    if hasattr(getTotSteps, "__len__") and getTotSteps.__len__() < 1:
        return legends_HTML

    for row in getTotSteps:
        TotSteps = row['totsteps']
        TotColorLabels = row['totcolorlabels']
        TotGroupLabels = row['totgrouplabels']

    for row in legend_info:
        # legend_dict = functions.row2dict(row)
        legendName = row['legend_name']  # .decode('utf-8')

    # legendName = legendName.encode('utf-8', errors='ignore')
    legendNameHorizontal = u''.join(legendName).encode('utf-8')
    legendNameHorizontal = re.sub('<br>|<BR>|</br>|</BR>', ' ',
                                  legendNameHorizontal.decode())
    # legendNameHorizontal = legendNameHorizontal.decode('utf-8')

    ######################################
    # Create horizontal legend
    ######################################

    if TotSteps >= 30:
        fontSizeLabels = 12
        fontSizeTitle = 15
        # stepWidth = 28
        legendWidth = 500  # 775
        legendTableBegin = '<table style="border-spacing:0px; background:white; padding: 5px 35px 5px 5px;"> '
        legendHeader = '<tr><td colspan=' + str(
            TotSteps
        ) + ' style="font-weight: bold; background:white; padding: 0px 5px 5px 0px; font-size:' + str(
            fontSizeTitle) + 'px;">' + legendNameHorizontal + '</td></tr>'

        if TotColorLabels > 0:
            ColumnSpan = math.ceil(TotSteps / float(TotColorLabels))
        else:
            ColumnSpan = 1

        if TotSteps > 30:
            stepWidth = old_div(legendWidth, TotSteps)
        else:
            stepWidth = 15

        if stepWidth < 4:
            stepWidth = 1

        legendColors = '<tr style="border-spacing: 0px;">'
        for row in legend_steps:
            # convert row['color_rgb'] from RGB to html color
            color_rgb = row.color_rgb.split(' ')
            color_html = functions.rgb2html(color_rgb)
            r = color_rgb[0]
            g = color_rgb[1]
            b = color_rgb[2]
            color_html = 'rgb(' + r + ',' + g + ',' + b + ')'

            border = ""
            if TotSteps <= 30:
                border = "border:1px solid black; "

            legendColors = legendColors + '<td width=' + str(
                stepWidth
            ) + 'px; height=15px; style="' + border + ' background-color: ' + color_html + '"></td>'
        legendColors += '</tr>'

        legendColorLabels = '<tr style="border-spacing: 0px;">'
        skipcolumns = 0
        ColSpan = ColumnSpan
        if ColumnSpan > 15:
            ColSpan = 10
        labelcounter = 0
        rowcounter = 0
        # ColSpan = 5
        for row in legend_steps:
            rowcounter += 1
            if row.color_label != None and row.color_label.strip() != '':
                labelcounter += 1
                if labelcounter == TotColorLabels:
                    ColSpan = TotSteps - rowcounter
                legendColorLabels += '<td colspan="' + str(int(ColSpan)) + '" style="font-weight: bold; font-size:' + \
                                     str(fontSizeLabels) + 'px; line-height:24px; max-width:' + \
                                     str(stepWidth + 5) + 'px;" align="left">' + row.color_label + '</td>'
                skipcolumns = int(ColSpan - 1)
            elif skipcolumns > 0:
                skipcolumns -= 1
            else:
                legendColorLabels += '<td width="1px;"></td>'

        legendColorLabels += '</tr>'

        legendTableEnd = '</table>'

        legendHTMLHorizontal = legendTableBegin + legendHeader + legendColors + legendColorLabels + legendTableEnd
    else:
        mainTable = '<table style="background: white; border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing:0px; cellpadding:0px; margin: 0px; padding: 2px 10px 2px 2px; ">'
        mainTable += '<tr><td colspan=1 style="font-weight: bold; font-size:15px; ">' + legendNameHorizontal + '</td></tr>'  # line-height:24px !important;;  padding-left: 15px;
        mainTable += '<tr><td>'
        mainTable += '<table class="table-header-rotated">'
        mainTableBody = '<tbody>'
        colorRow = '<tr><td width=28px; height=15px;></td>'
        tickRow = '<tr><td width=28px; height=6px;></td>'
        footer = '<tfoot><tr>'

        row_counter = 0
        for row in legend_steps:
            row_counter += 1

            if row.color_label == None:
                color_label = ''
            else:
                color_label = row.color_label.strip()

            if row_counter == 1:
                borderleft = ' border-left:1px solid black; '
                if len(color_label) > 4:
                    colorRow = '<tr><td width=45px; height=15px;></td>'
                    tickRow = '<tr><td width=45px; height=6px;></td>'
            else:
                borderleft = ''

            borderright = ''
            if row_counter == legend_steps.__len__():
                borderright = ' border-right:1px solid black; '
                # if row.group_label != None and row.group_label.strip() != '':
                #     absoluteMaxHeader = '<th class="rotate-45"><div><span>'+row.group_label+'</span></div></th>'

            # Add color column
            # convert row['color_rgb'] from RGB to html color
            color_rgb = row.color_rgb.split(' ')
            # color_html = functions.rgb2html(color_rgb)
            r = color_rgb[0]
            g = color_rgb[1]
            b = color_rgb[2]
            color_html = 'rgb(' + r + ',' + g + ',' + b + ')'

            colorRow += '<td width=20px; height=15px; style="border-top:1px solid black; ' + borderleft + borderright + ' background-color: ' + color_html + '"></td>'
            tickRow += '<td width=20px; height=6px; style="border-top:1px solid black; border-right:1px solid black; ' + borderleft + ' "></td>'
            absoluteMaxHeader = ''

            left = ''
            if row_counter == 1:
                height = "32px"
                if len(color_label) > 4:
                    textalign = 'center'
                    bottom = '25px'
                    left = ' left:-20px !important; '
                elif len(color_label) == 4:
                    textalign = 'center'
                    bottom = '12px'
                    left = ' left:-18px !important; '
                else:
                    textalign = 'center'
                    bottom = '17px'
                    left = ' left:-15px !important; '

                # footer += '<th class="rotate-45" height="32px"><div><span style="text-align:start; bottom: 26px;">' + color_label + '</span></div></th>'
            elif row_counter == legend_steps.__len__():
                if row.group_label != None and row.group_label.strip() != '':
                    height = "25px"
                    textalign = 'justify'
                    if len(row.group_label) >= 4:
                        bottom = '28px'
                    elif len(row.group_label) == 1:
                        bottom = '40px'
                    elif len(row.group_label) == 2:
                        bottom = '38px'
                    elif len(row.group_label) == 3:
                        bottom = '34px'
                    # absoluteMaxHeader = '<th class="rotate-45"><div><span>'+row.group_label+'</span></div></th>'
                    absoluteMaxHeader = '<th class="rotate-45" height="' + height + '"><div><span style="text-align:' + textalign + '; bottom: ' + bottom + ';">' + row.group_label + '</span></div></th>'
            else:
                height = "25px"
                textalign = 'justify'
                if len(color_label) >= 4:
                    bottom = '28px'
                elif len(color_label) == 1:
                    bottom = '40px'
                elif len(color_label) == 2:
                    bottom = '38px'
                elif len(color_label) == 3:
                    bottom = '34px'

            footer += '<th class="rotate-45" height="' + height + '"><div><span style="text-align:' + textalign + '; bottom: ' + bottom + ';' + left + '">' + color_label + '</span></div></th>'
            footer += absoluteMaxHeader

        colorRow += '</tr>'
        tickRow += '</tr>'
        footer += '</tr></tfoot>'
        mainTableBody += colorRow + tickRow + '</tbody>'
        mainTable += mainTableBody + footer + '</table></td></tr></table>'
        legendHTMLHorizontal = mainTable

    ######################################
    # Create vertical legend
    ######################################
    if TotSteps >= 25:
        fontSizeLabels = 12
        fontSizeTitle = 15
        stepWidth = 28
        stepHeight = 1
        rowspanlabel = 15
        lineheight = 12
        classlegendstyle = "legend-style"

        if TotSteps <= 35:
            stepHeight = 10
            rowspanlabel = 2
            classlegendstyle = ''
        elif TotSteps <= 65:
            stepHeight = 3
            rowspanlabel = 4
            classlegendstyle = ''
        elif TotSteps <= 130:
            stepHeight = 2
            rowspanlabel = 6
            classlegendstyle = ''

        mainTableBegin = '<table style="border-spacing:0px; background:white; padding:0;"> '
        mainTableEnd = '</table>'
        legendHeaderRow = '<tr><td style="font-weight: bold;background:white; padding: 5px; font-size:' + str(
            fontSizeTitle) + 'px;">' + legendName + '</td></tr>'
        legendTableBegin = '<table style="border-spacing:0px; background:white; padding: 0px 1px 0px 1px;"> '
        legendTableEnd = '</table>'

        # if TotColorLabels > 0:
        #     rowspanlabel = math.ceil(TotSteps / float(TotColorLabels))
        # else:
        #     rowspanlabel = 1

        Counter = 0
        for row in legend_steps:

            # Add color column
            # convert row['color_rgb'] from RGB to html color
            color_rgb = row.color_rgb.split(' ')
            color_html = functions.rgb2html(color_rgb)
            r = color_rgb[0]
            g = color_rgb[1]
            b = color_rgb[2]
            color_html = 'rgb(' + r + ',' + g + ',' + b + ')'

            border = ""
            if TotSteps <= 24:
                border = "border:1px solid black; "

            # legendColorColumn = '<td width='+str(stepWidth)+'px; height='+str(stepHeight)+'px; style="'+border+' background-color: '+color_html+'"></td>'
            legendColorColumn = '<td width=' + str(
                stepWidth
            ) + 'px; class="' + classlegendstyle + '" style="' + border + ' background-color: ' + color_html + '"></td>'

            # Add label column
            Counter += 1
            if Counter == 1 and row.color_label != None and row.color_label.strip(
            ) != '':
                rowspan = 1
            else:
                rowspan = rowspanlabel

            legendColorLabelColumn = '<td class="' + classlegendstyle + '"></td>'
            if rowspanlabel > 1:
                if row.color_label != None and row.color_label.strip() != '':
                    legendColorLabelColumn = '<td rowspan="' + str(
                        rowspan
                    ) + 'px;" style="font-weight: bold; font-size:' + str(
                        fontSizeLabels
                    ) + 'px; line-height:' + str(
                        lineheight
                    ) + 'px;" valign="top" align="left">' + row.color_label + '</td>'
            else:
                # legendstep_dict = functions.row2dict(row)
                if row.color_label != None and row.color_label.strip() != '':
                    legendColorLabelColumn = '<td rowspan="' + str(
                        rowspan
                    ) + 'px;" style="font-weight: bold; font-size:' + str(
                        fontSizeLabels) + 'px; line-height:' + str(
                            lineheight
                        ) + 'px;" align="left">' + row.color_label + '</td>'

            legendHTMLVertical += '<tr style="height:' + str(
                stepHeight
            ) + 'px;">' + legendColorColumn + legendColorLabelColumn + '</tr>'

            # Add an empty row for the label on last class to have the lable shown at the bottom of the table
            if TotSteps == Counter and row.color_label != None and row.color_label.strip(
            ) != '':
                legendHTMLVertical += '<tr style="height:1px;"></tr>'

        legendHTMLVertical = mainTableBegin + legendHeaderRow + '<tr><td>' + legendTableBegin + legendHTMLVertical + legendTableEnd + '</td></tr>' + mainTableEnd

    else:
        mainTableBackgroundColor = 'transparent'
        fontSizeHeader = 15
        fontSizeLabels = 12
        firstColumnWidth = 35
        legendColorTableBackgroundColor = 'white'
        legendLabelTableBackgroundColor = 'white'
        extraFirstRowHeight = 10
        absoluteMaxRowColorTableHeight = 7
        colorColumnWidth = 35
        colorColumnHeight = 12
        tickColumnWidth = 8
        tickColumnHeight = 12
        labelColumnHeight = 12
        lineheight = 12

        mainTableBegin = '<table style="background: ' + mainTableBackgroundColor + '; border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding: 0px; ">'
        legendHeaderRow = '<tr><td colspan=2 style="font-weight: bold; background: white; padding:2px;"><span style=" font-size:' + str(
            fontSizeHeader
        ) + 'px;">' + legendName + '</span></td></tr>'  # line-height: 24px;
        legendRowBegin = '<tr>'
        firstColumnBegin = '<td width=' + str(
            firstColumnWidth
        ) + 'px; style="border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding: 0px;">'
        secondColumnBegin = '<td valign="top" align="left" style="border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding: 0px;" >'

        legendColorTable = '<table style="background: ' + legendColorTableBackgroundColor + '; border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding-left: 3px;">'
        legendColorTable += '<tr><td colspan=2 height=' + str(
            extraFirstRowHeight) + 'px; style=""></td></tr>'

        legendLabelTable = '<table style="background: ' + legendLabelTableBackgroundColor + '; border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding: 0px; ">'

        row_counter = 0
        # print ('legend_steps: ' + str(legend_steps.__len__()))
        for row in legend_steps:
            row_counter += 1
            if row_counter == 1:
                bordertop = ' border-top:1px solid black; '
                lineheight = 15
            elif row_counter == legend_steps.__len__():
                lineheight = 13
            else:
                bordertop = ' '
                lineheight = 12

            borderbottom = ' '
            borderbottomtick = ' '
            absoluteMaxRowColorTable = ''
            absoluteMaxRowLegendLabelTable = ''
            if row_counter == legend_steps.__len__():
                borderbottom = ' border-bottom:1px solid black; '
                if row.group_label != None and row.group_label.strip() != '':
                    borderbottomtick = ' border-bottom:1px solid black; '
                    absoluteMaxRowColorTable = '<tr><td colspan=2 height=' + str(
                        absoluteMaxRowColorTableHeight
                    ) + 'px; style=""></td></tr>'
                    absoluteMaxRowLegendLabelTable = '<tr><td height=' + str(
                        labelColumnHeight
                    ) + 'px; style="font-weight: bold; font-size:' + str(
                        fontSizeLabels
                    ) + 'px; line-height:' + str(
                        lineheight
                    ) + 'px; padding:0px; margin: 0px; padding-left:5px;" valign="middle" align="left">' + row.group_label + '</td></tr>'

            # Add color column
            # convert row['color_rgb'] from RGB to html color
            color_rgb = row.color_rgb.split(' ')
            # color_html = functions.rgb2html(color_rgb)
            r = color_rgb[0]
            g = color_rgb[1]
            b = color_rgb[2]
            color_html = 'rgb(' + r + ',' + g + ',' + b + ')'

            legendColorTable += '<tr> ' + \
                '<td width='+str(colorColumnWidth)+'px; height='+str(colorColumnHeight)+'px; style="padding:0px; margin: 0px; border-left:1px solid black; '+borderbottom+bordertop+' background-color: '+color_html+'"></td>' + \
                '<td width='+str(tickColumnWidth)+'px; height='+str(tickColumnHeight)+'px; style="padding:0px; margin: 0px; border-top:1pt solid black; border-left:1px solid black; '+borderbottomtick+'"></td>' + \
            '</tr>'

            legendColorTable += absoluteMaxRowColorTable

            if row.color_label == None:
                color_label = ''
            else:
                color_label = row.color_label.strip()
            legendLabelTable += '<tr><td height=' + str(
                labelColumnHeight
            ) + 'px; style="font-weight: bold; font-size:' + str(
                fontSizeLabels
            ) + 'px; line-height:' + str(
                lineheight
            ) + 'px; padding:0px; margin: 0px; padding-left:5px;" valign="middle" align="left">' + color_label + '</td></tr>'

            legendLabelTable += absoluteMaxRowLegendLabelTable

        legendColorTable += '</table>'
        # legendLabelTable += '<tr><td height=' + str(extraFirstRowHeight) + 'px; style=""></td></tr>'
        legendLabelTable += '</table>'

        columnEnd = '</td>'
        legendRowEnd = '</tr>'
        mainTableEnd = '</table>'

        legendHTMLVertical = mainTableBegin + legendHeaderRow + legendRowBegin + firstColumnBegin + legendColorTable + columnEnd + secondColumnBegin + legendLabelTable + columnEnd + legendRowEnd + mainTableEnd
        # print legendHTMLVertical

    legends_HTML = {
        'legendHTML': legendHTMLHorizontal,
        'legendHTMLVertical': legendHTMLVertical
    }

    return legends_HTML
Beispiel #4
0
def generateLegendHTML(legend_id):
    legendHTMLHorizontal = ''
    legendHTMLVertical = ''
    legendName = ''
    TotSteps = 0
    TotColorLabels = 0
    TotGroupLabels = 0
    legends_HTML = {'legendHTML': '', 'legendHTMLVertical': ''}

    if legend_id == None:
        return legends_HTML

    # print('legend_id: ' + str(legend_id))
    legend_info = querydb.get_legend_info(legendid=legend_id)
    if hasattr(legend_info, "__len__") and legend_info.__len__() < 1:
        return legends_HTML

    legend_steps = querydb.get_legend_steps(legendid=legend_id)
    if hasattr(legend_steps, "__len__") and legend_steps.__len__() < 1:
        return legends_HTML

    getTotSteps = querydb.get_legend_totals(legendid=legend_id)
    if hasattr(getTotSteps, "__len__") and getTotSteps.__len__() < 1:
        return legends_HTML

    for row in getTotSteps:
        TotSteps = row['totsteps']
        TotColorLabels = row['totcolorlabels']
        TotGroupLabels = row['totgrouplabels']

    for row in legend_info:
        # legend_dict = functions.row2dict(row)
        legendName = row['legend_name']

    ######################################
    # Create horizontal legend
    ######################################

    if TotSteps >= 35:
        fontSizeLabels = 16
        fontSizeTitle = 18
        # stepWidth = 28
        legendWidth = 500  # 775
        legendTableBegin = '<table style="border-spacing:0px; background:white; padding: 5px 35px 5px 5px;"> '
        legendHeader = '<tr><td colspan=' + str(
            TotSteps
        ) + ' style="font-weight: bold; background:white; padding: 0px 5px 5px 0px; font-size:' + str(
            fontSizeTitle) + 'px;">' + legendName + '</td></tr>'

        if TotColorLabels > 0:
            ColumnSpan = math.ceil(TotSteps / float(TotColorLabels))
        else:
            ColumnSpan = 1

        if TotSteps > 60:
            stepWidth = legendWidth / TotSteps
        else:
            stepWidth = 50

        if stepWidth < 4:
            stepWidth = 1

        legendColors = '<tr style="border-spacing: 0px;">'
        for row in legend_steps:
            # convert row['color_rgb'] from RGB to html color
            color_rgb = row.color_rgb.split(' ')
            color_html = functions.rgb2html(color_rgb)
            r = color_rgb[0]
            g = color_rgb[1]
            b = color_rgb[2]
            color_html = 'rgb(' + r + ',' + g + ',' + b + ')'

            border = ""
            if TotSteps <= 30:
                border = "border:1px solid black; "

            legendColors = legendColors + '<td width=' + str(
                stepWidth
            ) + 'px; height=15px; style="' + border + ' background-color: ' + color_html + '"></td>'
        legendColors += '</tr>'

        legendColorLabels = '<tr style="border-spacing: 0px;">'
        skipcolumns = 0
        ColSpan = ColumnSpan
        if ColumnSpan > 15:
            ColSpan = 10
        labelcounter = 0
        rowcounter = 0
        # ColSpan = 5
        for row in legend_steps:
            rowcounter += 1
            if row.color_label != None and row.color_label.strip() != '':
                labelcounter += 1
                if labelcounter == TotColorLabels:
                    ColSpan = TotSteps - rowcounter
                legendColorLabels += '<td colspan="' + str(
                    int(ColSpan)
                ) + '" style="font-weight: bold; font-size:' + str(
                    fontSizeLabels) + 'px; line-height:24px; max-width:' + str(
                        stepWidth +
                        5) + 'px;" align="left">' + row.color_label + '</td>'
                skipcolumns = int(ColSpan - 1)
            elif skipcolumns > 0:
                skipcolumns -= 1
            else:
                legendColorLabels += '<td width="1px;"></td>'

        legendColorLabels += '</tr>'

        legendTableEnd = '</table>'

        legendHTMLHorizontal = legendTableBegin + legendHeader + legendColors + legendColorLabels + legendTableEnd
    else:
        mainTable = '<table style="background: white; border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing:0px; cellpadding:0px; margin: 0px; padding: 10px; ">'
        mainTable += '<tr><td colspan=1 style="font-weight: bold; font-size:18px; line-height:24px !important;">' + legendName + '</td></tr>'  # line-height:26px;
        mainTable += '<tr><td>'
        mainTable += '<table class="table table-striped table-header-rotated">'
        mainTableBody = '<tbody>'
        colorRow = '<tr><td width=25px; height=22px;></td>'
        tickRow = '<tr><td width=25px; height=6px;></td>'
        footer = '<tfoot><tr>'

        row_counter = 0
        for row in legend_steps:
            row_counter += 1
            if row_counter == 1:
                borderleft = ' border-left:1px solid black; '
            else:
                borderleft = ''

            borderright = ''
            absoluteMaxHeader = ''
            if row_counter == legend_steps.__len__():
                borderright = ' border-right:1px solid black; '
                if row.group_label != None and row.group_label.strip() != '':
                    absoluteMaxHeader = '<th class="rotate-45"><div><span>' + row.group_label + '</span></div></th>'

            # Add color column
            # convert row['color_rgb'] from RGB to html color
            color_rgb = row.color_rgb.split(' ')
            # color_html = functions.rgb2html(color_rgb)
            r = color_rgb[0]
            g = color_rgb[1]
            b = color_rgb[2]
            color_html = 'rgb(' + r + ',' + g + ',' + b + ')'

            colorRow += '<td width=25px; height=22px; style="border-top:1px solid black; ' + borderleft + borderright + ' background-color: ' + color_html + '"></td>'
            tickRow += '<td width=25px; height=6px; style="border-top:1px solid black; border-right:1px solid black; ' + borderleft + ' "></td>'
            if row.color_label == None:
                color_label = ''
            else:
                color_label = row.color_label.strip()

            footer += '<th class="rotate-45"><div><span>' + color_label + '</span></div></th>'  # style="line-height:65px !important;"
            footer += absoluteMaxHeader

        colorRow += '</tr>'
        tickRow += '</tr>'
        footer += '</tr></tfoot>'
        mainTableBody += colorRow + tickRow + '</tbody>'
        mainTable += mainTableBody + footer + '</table></td></tr></table>'
        legendHTMLHorizontal = mainTable

    ######################################
    # Create vertical legend
    ######################################
    if TotSteps >= 25:
        fontSizeLabels = 16
        fontSizeTitle = 18
        stepWidth = 28
        stepHeight = 1
        if TotSteps <= 35:
            stepHeight = 15
        elif TotSteps <= 65:
            stepHeight = 5
        elif TotSteps <= 115:
            stepHeight = 3

        mainTableBegin = '<table style="border-spacing:0px; background:white; padding:0;"> '
        mainTableEnd = '</table>'
        legendHeaderRow = '<tr><td style="font-weight: bold;background:white; padding: 5px; font-size:' + str(
            fontSizeTitle) + 'px;">' + legendName + '</td></tr>'
        legendTableBegin = '<table style="border-spacing:0px; background:white; padding: 5px 5px 10px 10px;"> '
        legendTableEnd = '</table>'

        if TotColorLabels > 0:
            ColumnSpan = math.ceil(TotSteps / float(TotColorLabels))
        else:
            ColumnSpan = 1

        Counter = 0
        for row in legend_steps:

            # Add color column
            # convert row['color_rgb'] from RGB to html color
            color_rgb = row.color_rgb.split(' ')
            color_html = functions.rgb2html(color_rgb)
            r = color_rgb[0]
            g = color_rgb[1]
            b = color_rgb[2]
            color_html = 'rgb(' + r + ',' + g + ',' + b + ')'

            border = ""
            if TotSteps <= 24:
                border = "border:1px solid black; "

            legendColorColumn = '<td width=' + str(
                stepWidth
            ) + 'px; height=' + str(
                stepHeight
            ) + 'px; style="' + border + ' background-color: ' + color_html + '"></td>'

            # Add label column
            Counter += 1
            legendColorLabelColumn = '<td height="1px;"></td>'
            if ColumnSpan > 1:
                if row.color_label != None and row.color_label.strip() != '':
                    # legendColorLabelColumn = '<td rowspan="' + str(ColumnSpan) + '" style="font-size:9px; line-height:10px; " valign="top" align="center">'+row.color_label+'</td>'
                    legendColorLabelColumn = '<td rowspan=5 style="font-weight: bold; font-size:' + str(
                        fontSizeLabels
                    ) + 'px; line-height:10px; " valign="top" align="left">' + row.color_label + '</td>'
            else:
                legendstep_dict = functions.row2dict(row)
                if row.color_label != None and row.color_label.strip() != '':
                    # ColorLabel = '&nbsp;'+legendstep_dict['color_label'].strip()+'&nbsp;'
                    legendColorLabelColumn = '<td rowspan="' + str(
                        ColumnSpan
                    ) + '" style="font-weight: bold; font-size:' + str(
                        fontSizeLabels
                    ) + 'px; line-height:10px; " align="left">' + row.color_label + '</td>'

            legendHTMLVertical += '<tr>' + legendColorColumn + legendColorLabelColumn + '</tr>'

        legendHTMLVertical = mainTableBegin + legendHeaderRow + '<tr><td>' + legendTableBegin + legendHTMLVertical + legendTableEnd + '</td></tr>' + mainTableEnd

    else:
        mainTableBackgroundColor = 'transparent'
        fontSizeHeader = 18
        fontSizeLabels = 16
        firstColumnWidth = 35
        legendColorTableBackgroundColor = 'white'
        legendLabelTableBackgroundColor = 'white'
        extraFirstRowHeight = 14
        absoluteMaxRowColorTableHeight = 18
        colorColumnWidth = 35
        colorColumnHeight = 20
        tickColumnWidth = 8
        tickColumnHeight = 20
        labelColumnHeight = 20

        mainTableBegin = '<table style="background: ' + mainTableBackgroundColor + '; border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding: 0px; ">'
        legendHeaderRow = '<tr><td colspan=2 style="font-weight: bold; background: white; padding:3px;"><span style=" font-size:' + str(
            fontSizeHeader
        ) + 'px;">' + legendName + '</span></td></tr>'  # line-height: 24px;
        legendRowBegin = '<tr>'
        firstColumnBegin = '<td width=' + str(
            firstColumnWidth
        ) + 'px; style="border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding: 0px;">'
        secondColumnBegin = '<td valign="top" align="left" style="border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding: 0px;" >'

        legendColorTable = '<table style="background: ' + legendColorTableBackgroundColor + '; border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding-left: 3px;">'
        legendColorTable += '<tr><td colspan=2 height=' + str(
            extraFirstRowHeight) + 'px; style=""></td></tr>'

        legendLabelTable = '<table style="background: ' + legendLabelTableBackgroundColor + '; border:0px solid black; border-spacing:0px; border-padding:0px; cellspacing=0px; cellpadding=0px; margin: 0px; padding: 3px; ">'

        row_counter = 0
        # print('legend_steps: ' + str(legend_steps.__len__()))
        for row in legend_steps:
            row_counter += 1
            if row_counter == 1:
                bordertop = ' border-top:1px solid black; '
            else:
                bordertop = ' '

            borderbottom = ' '
            borderbottomtick = ' '
            absoluteMaxRowColorTable = ''
            absoluteMaxRowLegendLabelTable = ''
            if row_counter == legend_steps.__len__():
                borderbottom = ' border-bottom:1px solid black; '
                if row.group_label != None and row.group_label.strip() != '':
                    borderbottomtick = ' border-bottom:1px solid black; '
                    absoluteMaxRowColorTable = '<tr><td colspan=2 height=' + str(
                        absoluteMaxRowColorTableHeight
                    ) + 'px; style=""></td></tr>'
                    absoluteMaxRowLegendLabelTable = '<tr><td height=' + str(
                        labelColumnHeight
                    ) + 'px; style="font-weight: bold; font-size:' + str(
                        fontSizeLabels
                    ) + 'px;  padding:0px; margin: 0px; padding-left:5px;" valign="middle" align="left">' + row.group_label + '</td></tr>'

            # Add color column
            # convert row['color_rgb'] from RGB to html color
            color_rgb = row.color_rgb.split(' ')
            # color_html = functions.rgb2html(color_rgb)
            r = color_rgb[0]
            g = color_rgb[1]
            b = color_rgb[2]
            color_html = 'rgb(' + r + ',' + g + ',' + b + ')'

            legendColorTable += '<tr> ' + \
                '<td width='+str(colorColumnWidth)+'px; height='+str(colorColumnHeight)+'px; style="padding:0px; margin: 0px; border-left:1px solid black; '+borderbottom+bordertop+' background-color: '+color_html+'"></td>' + \
                '<td width='+str(tickColumnWidth)+'px; height='+str(tickColumnHeight)+'px; style="padding:0px; margin: 0px; border-top:1pt solid black; border-left:1px solid black; '+borderbottomtick+'"></td>' + \
            '</tr>'

            legendColorTable += absoluteMaxRowColorTable

            if row.color_label == None:
                color_label = ''
            else:
                color_label = row.color_label.strip()
            legendLabelTable += '<tr><td height=' + str(
                labelColumnHeight
            ) + 'px; style="font-weight: bold; font-size:' + str(
                fontSizeLabels
            ) + 'px;  padding:0px; margin: 0px; padding-left:5px;" valign="middle" align="left">' + color_label + '</td></tr>'

            legendLabelTable += absoluteMaxRowLegendLabelTable

        legendColorTable += '</table>'
        # legendLabelTable += '<tr><td height=' + str(extraFirstRowHeight) + 'px; style=""></td></tr>'
        legendLabelTable += '</table>'

        columnEnd = '</td>'
        legendRowEnd = '</tr>'
        mainTableEnd = '</table>'

        legendHTMLVertical = mainTableBegin + legendHeaderRow + legendRowBegin + firstColumnBegin + legendColorTable + columnEnd + secondColumnBegin + legendLabelTable + columnEnd + legendRowEnd + mainTableEnd
        # print legendHTMLVertical

    legends_HTML = {
        'legendHTML': legendHTMLHorizontal,
        'legendHTMLVertical': legendHTMLVertical
    }
    return legends_HTML
def createSLD(product, version, subproduct, output_file=None):
    if output_file is None:
        output_file = '{0}/{1}_{2}_{3}.sld'.format(tempDir, product, version,
                                                   subproduct)

    # make sure /data/temp exists
    # Note 1: see http://stackoverflow.com/questions/273192/how-to-check-if-a-directory-exists-and-create-it-if-necessary
    # Note 2: /data/temp should be a variable
    if not os.path.exists(tempDir):
        os.makedirs(tempDir)

    product_legends = querydb.get_product_legends(productcode=product,
                                                  subproductcode=subproduct,
                                                  version=version)

    # Get scale factor
    product_info = querydb.get_product_out_info(productcode=product,
                                                subproductcode=subproduct,
                                                version=version)
    scale_factor = product_info[0].scale_factor

    if hasattr(product_legends, "__len__") and product_legends.__len__() > 0:

        for legend in product_legends:

            # Changes for ES2-85
            legend_dict = legend
            defaultlegend = legend_dict['default_legend']

            # Changes for ES2-85
            # if default_legend == 'True':
            #     defaultlegend = True
            # else:
            #     defaultlegend = False

            # if there is only 1 legend defined, this is the default legend (even if not defined as default legend).
            if product_legends.__len__() == 1:
                defaultlegend = True

            if defaultlegend:
                legend_id = legend_dict['legend_id']
                legend_steps = querydb.get_legend_steps(legendid=legend_id)
                legend_name = legend_dict['legend_name']

    else:
        logger.warning('Error: no legend exists for this product. Exit')
        return 1

    num_steps = len(legend_steps)

    # Read the schema from the template
    tree = ET.ElementTree(file=geoserverREST.templ_sld)

    # Modify the schema for that Legend
    # Modify Layer Name
    for child in tree.getiterator():
        if child.tag == 'NamedLayer':
            child.set("Name", product)

    # Modify User Style Title
    for child in tree.getiterator():
        if child.tag == 'UserStyle':
            child.set("Title", legend_name)

    # Modify the Steps (and remove remaining ones)
    for child in tree.getiterator():
        if child.tag == 'ColorMap':
            ColorMap = child
            num_CME = len(ColorMap)

            # Check there are enough CME for this legend
            if num_steps > num_CME:
                logger.error('Too many legend steps [>255]. Exit')
                return 1

            for istep in range(0, num_steps):
                step = legend_steps[istep]
                # Build the RGB color
                color_rgb = step.color_rgb.split(' ')
                r = color_rgb[0]
                g = color_rgb[1]
                b = color_rgb[2]
                color_html = rgb2html(color_rgb)

                to_value = old_div(step.to_step, scale_factor)

                # Modify steps
                ColorMap[istep].set('quantity', str(to_value))
                ColorMap[istep].set('color', color_html)

            for istep in range(num_steps, num_CME):
                del ColorMap[num_steps]

    tree.write(output_file)

    return output_file
    def test_get_productlayer(self):
        #import StringIO
        import mapscript
        # getparams = web.input()

        #getparams = {'STYLES': u'', 'productcode': u'vgt-ndvi', 'legendid': u'7', 'SERVICE': u'WMS', 'subproductcode': u'ndv', 'CRS': u'EPSG:4326', 'FORMAT': u'image/png', 'REQUEST': u'GetMap', 'HEIGHT': u'1010', 'WIDTH': u'998', 'VERSION': u'1.3.0', 'productversion': u'sv2-pv2.1', 'date': u'20130221', 'mapsetcode': u'SPOTV-Africa-1km', 'TRANSPARENT': u'false', 'BBOX': u'-16.17,16.17,-15.47,16.87'}
        getparams = {'STYLES': u'',
                     'productcode': u'vgt-fapar',
                     'legendid': u'99',
                     'SERVICE': u'WMS',
                     'subproductcode': u'fapar',
                     'CRS': u'EPSG:4326',
                     'FORMAT': u'image/png',
                     'REQUEST': u'GetMap',
                     'HEIGHT': u'1010',
                     'WIDTH': u'998',
                     'VERSION': u'1.3.0',
                     'productversion': u'V1.4',
                     'date': u'20130221',
                     'mapsetcode': u'SPOTV-Africa-1km',
                     'TRANSPARENT': u'false',
                     'BBOX': u'15.46875, -17.578125, 16.171875, -16.875'}

        #getparams = {'STYLES': u'', 'productcode': u'vgt-ndvi', 'legendid': u'7', 'SERVICE': u'WMS', 'subproductcode': u'ndv', 'CRS': u'EPSG:4326', 'FORMAT': u'image/png', 'REQUEST': u'GetMap', 'HEIGHT': u'1091', 'WIDTH': u'998', 'VERSION': u'1.3.0', 'productversion': u'sv2-pv2.1', 'date': u'20130221', 'mapsetcode': u'SPOTV-Africa-1km', 'TRANSPARENT': u'false', 'BBOX': u'-25.70957541665903,9.276714800828785,-13.723491432284028,20.021343707078785'}
        # getparams = [
        #     SERVICE:'WMS',
        #     VERSION='1.3.0',
        #     REQUEST='GetMap',
        #     FORMAT='image/png',
        #     TRANSPARENT='false',
        #     productcode='vgt-ndvi',
        #     productversion='sv2-pv2.1',
        #     subproductcode='ndv',
        #     mapsetcode='SPOTV-Africa-1km',
        #     legendid='7',
        #     date='20130221',
        #     CRS='EPSG:4326'',
        #     STYLES=''
        #     WIDTH='998',
        #     HEIGHT='1010',
        #     BBOX='-26,-35,60,38'
        # ]
        p = Product(product_code=getparams['productcode'], version=getparams['productversion'])
        dataset = p.get_dataset(mapset=getparams['mapsetcode'], sub_product_code=getparams['subproductcode'])
        # print dataset.fullpath

        if hasattr(getparams, "date"):
            filedate = getparams['date']
        else:
            dataset.get_filenames()
            lastdate = dataset.get_dates()[-1].strftime("%Y%m%d")
            filedate = lastdate

        if dataset.no_year():
            filedate=dataset.strip_year(filedate)
        # lastdate = lastdate.replace("-", "")
        # mydate=lastdate.strftime("%Y%m%d")

        filename = functions.set_path_filename(filedate,
                                               getparams['productcode'],
                                               getparams['subproductcode'],
                                               getparams['mapsetcode'],
                                               getparams['productversion'],
                                               '.tif')
        productfile = dataset.fullpath + filename
        # print productfile

        #web.header('Content-type', 'image/png')
        #web.header('Content-transfer-encoding', 'binary')
        #buf = StringIO.StringIO()
        #mapscript.msIO_installStdoutToBuffer()
        #map = mapserver.getmap()
        ##map.save to a file fname.png
        ##web.header('Content-Disposition', 'attachment; filename="fname.png"')
        #contents = buf.getvalue()
        #return contents

        #logger.debug("MapServer: Installing stdout to buffer.")
        mapscript.msIO_installStdoutToBuffer()

        # projlib = "/usr/share/proj/"
        projlib = es_constants.proj4_lib_dir
        # errorfile = es_constants.apps_dir+"/analysis/ms_tmp/ms_errors.log"
        errorfile = es_constants.log_dir+"/mapserver_error.log"
        # imagepath = es_constants.apps_dir+"/analysis/ms_tmp/"

        owsrequest = mapscript.OWSRequest()

        inputparams = getparams # web.input()
        for k, v in inputparams.iteritems():
            print k + ':' + v
            owsrequest.setParameter(k.upper(), v)

        # print owsrequest

        filenamenoextention = functions.set_path_filename(filedate,
                                               getparams['productcode'],
                                               getparams['subproductcode'],
                                               getparams['mapsetcode'],
                                               getparams['productversion'],
                                               '')
        owsrequest.setParameter("LAYERS", filenamenoextention)

        productmap = mapscript.mapObj(es_constants.template_mapfile)
        productmap.setConfigOption("PROJ_LIB", projlib)
        productmap.setConfigOption("MS_ERRORFILE", errorfile)
        productmap.maxsize = 4096

        outputformat_png = mapscript.outputFormatObj('GD/PNG', 'png')
        outputformat_png.setOption("INTERLACE", "OFF")
        productmap.appendOutputFormat(outputformat_png)
        #outputformat_gd = mapscript.outputFormatObj('GD/GIF', 'gif')
        #productmap.appendOutputFormat(outputformat_gd)
        productmap.selectOutputFormat('png')
        productmap.debug = mapscript.MS_TRUE
        productmap.status = mapscript.MS_ON
        productmap.units = mapscript.MS_DD

        coords = map(float, inputparams['BBOX'].split(","))
        print coords
        llx = coords[0]
        lly = coords[1]
        urx = coords[2]
        ury = coords[3]
        print llx, lly, urx, ury

        productmap.setExtent(llx, lly, urx, ury)   # -26, -35, 60, 38
        # productmap.setExtent(-26, -35, 60, 38)

        # epsg must be in lowercase because in unix/linux systems the proj filenames are lowercase!
        # epsg = "+init=epsg:3857"
        # epsg = "+init=" + inputparams.CRS.lower()   # CRS = "EPSG:4326"
        epsg = inputparams['CRS'].lower()   # CRS = "EPSG:4326"
        productmap.setProjection(epsg)

        w = int(inputparams['WIDTH'])
        h = int(inputparams['HEIGHT'])
        productmap.setSize(w, h)

        # General web service information
        productmap.setMetaData("WMS_TITLE", "Product description")
        productmap.setMetaData("WMS_SRS", inputparams['CRS'].lower())
        # productmap.setMetaData("WMS_SRS", "epsg:3857")
        productmap.setMetaData("WMS_ABSTRACT", "A Web Map Service returning eStation2 raster layers.")
        productmap.setMetaData("WMS_ENABLE_REQUEST", "*")   # necessary!!

        product_info = querydb.get_product_out_info(productcode=inputparams['productcode'],
                                                    subproductcode=inputparams['subproductcode'],
                                                    version=inputparams['productversion'])
        if hasattr(product_info, "__len__") and product_info.__len__() > 0:
            for row in product_info:
                scale_factor = row.scale_factor
                scale_offset = row.scale_offset
                nodata = row.nodata

        legend_info = querydb.get_legend_info(legendid=inputparams['legendid'])
        if hasattr(legend_info, "__len__") and legend_info.__len__() > 0:
            for row in legend_info:
                minstep = int((row.min_value - scale_offset)/scale_factor)    #int(row.min_value*scale_factor+scale_offset)
                maxstep = int((row.max_value - scale_offset)/scale_factor)    # int(row.max_value*scale_factor+scale_offset)
                realminstep = int((row.realminstep - scale_offset)/scale_factor)
                realmaxstep = int((row.realmaxstep - scale_offset)/scale_factor)
                minstepwidth = int((row.minstepwidth - scale_offset)/scale_factor)
                maxstepwidth = int((row.maxstepwidth - scale_offset)/scale_factor)
                totwidth = int((row.totwidth - scale_offset)/scale_factor)
                totsteps = row.totsteps

            # maxstep = 255
            processing_scale = 'SCALE='+str(minstep)+','+str(maxstep)  # min(legend_step.from_step) max(legend_step.to_step) example: 'SCALE=-7000,10000'

            minbuckets = 256
            maxbuckets = 10000
            num_buckets = maxbuckets
            if minstepwidth > 0:
                num_buckets = round(totwidth / minstepwidth, 0)

            if num_buckets < minbuckets:
                num_buckets = minbuckets
            elif num_buckets > maxbuckets:
                num_buckets = 0

            # num_buckets = 10000
            if num_buckets > 0:
                processing_buckets = 'SCALE_BUCKETS='+str(num_buckets)

            # nodata = -32768     # get this value from the table products.product
            processing_novalue = ''
            if nodata is not None and minstep <= nodata < maxstep:
                processing_novalue = 'NODATA='+str(nodata)

            layer = mapscript.layerObj(productmap)
            layer.name = filenamenoextention
            layer.type = mapscript.MS_LAYER_RASTER
            layer.status = mapscript.MS_ON     # MS_DEFAULT
            layer.data = productfile
            # layer.setProjection("+init=epsg:4326")
            layer.setProjection("epsg:4326")
            layer.dump = mapscript.MS_TRUE

            # scale & buckets
            if num_buckets > 0:
                layer.setProcessing(processing_scale)
                layer.setProcessing(processing_buckets)

            if processing_novalue != '':
                layer.setProcessing(processing_novalue)

            legend_steps = querydb.get_legend_steps(legendid=inputparams['legendid'])
            if hasattr(legend_steps, "__len__") and legend_steps.__len__() > 0:
                stepcount = 0
                for step in legend_steps:
                    stepcount += 1
                    min_step = int((step.from_step - scale_offset)/scale_factor)
                    max_step = int((step.to_step - scale_offset)/scale_factor)
                    colors = map(int, (color.strip() for color in step.color_rgb.split(" ") if color.strip()))

                    if stepcount == legend_steps.__len__():    # For the last step use <= max_step
                        expression_string = '([pixel] >= '+str(min_step)+' and [pixel] <= '+str(max_step)+')'
                    else:
                        expression_string = '([pixel] >= '+str(min_step)+' and [pixel] < '+str(max_step)+')'
                    # define class object and style
                    layerclass = mapscript.classObj(layer)
                    layerclass.name = layer.name+'_'+str(stepcount)
                    layerclass.setExpression(expression_string)
                    style = mapscript.styleObj(layerclass)
                    style.color.setRGB(colors[0], colors[1], colors[2])

        result_map_file = es_constants.apps_dir+'/analysis/MAP_result.map'
        # if os.path.isfile(result_map_file):
        #     os.remove(result_map_file)
        productmap.save(result_map_file)
        image = productmap.draw()
        image.save(es_constants.apps_dir+'/analysis/'+filenamenoextention+'.png')

        contents = productmap.OWSDispatch(owsrequest)
        content_type = mapscript.msIO_stripStdoutBufferContentType()
        content = mapscript.msIO_getStdoutBufferBytes()
        #web.header = "Content-Type","%s; charset=utf-8"%content_type
        # web.header('Content-type', 'image/png')
        #web.header('Content-transfer-encoding', 'binary')
        # return content

        self.assertEquals(True, True)