#include "panel.h"
#include "main.h"
#include <stdint.h>
#include "hd44780.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

void update_lcd(const struct sdisplay *displayCursor, const struct smeasure *measureData) {
    char cBuffer[16];

//    printf("U: %02.1fV [%2.1fV]\n\rI: %1.02fA [%1.02fA]\n\r", measureData->fvoltage, measureData->fvoltage_req, measureData->fcurrent, measureData->fcurrent_req);

    sprintf(&cBuffer, "U: %02.1fV [%2.1fV]", measureData->fvoltage, measureData->fvoltage_req);
    HD44780_Puts(0, 0, &cBuffer);
    sprintf(&cBuffer, "I: %1.02fA [%1.02fA]", measureData->fcurrent, measureData->fcurrent_req);
    HD44780_Puts(0, 1, &cBuffer);

    if ( displayCursor->line ) {
        if ( displayCursor->position > 1 ) {
        	HD44780_CursorSet(10 + ( 2 - displayCursor->position ), displayCursor->line);
        } else {
        	HD44780_CursorSet(10 + ( 3 - displayCursor->position ), displayCursor->line);
        }
    } else {
        if ( displayCursor->position > 0 ) {
        	HD44780_CursorSet (10 + ( 2 - displayCursor->position ), displayCursor->line);
        } else {
        	HD44780_CursorSet (10 + ( 3 - displayCursor->position ), displayCursor->line);
        }
    }
}

void change_value(struct smeasure *measureData, struct sdisplay *displayCursor, uint8_t *ChangeValue) {
    float fadd, flimit, *fval;
    uint8_t i;
    if ( displayCursor->line == 0 ) {
    	fval = &measureData->fvoltage_req;
        flimit = 25.0;
        fadd = 0.1;
    } else {
    	fval = &measureData->fcurrent_req;
        flimit = 2.00;
        fadd = 0.01;
    }
    for (i = 0; i < displayCursor->position; i++) {
    	fadd = fadd * 10;
    }

    if ( *ChangeValue == UP  && ( *fval + fadd ) <= flimit ) {
        *fval = *fval + fadd;
    }
    if ( *ChangeValue == DOWN && ( *fval - fadd ) >= 0 ) {
        *fval = *fval - fadd;
    }
    *ChangeValue = 0;
}

