#include "../include/console.h"
#include <Uefi.h>
#include <Library/BaseMemoryLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Library/BaseLib.h>
#include <Protocol/SimpleTextIn.h>
VOID bp_console_print_file(bp_disk_FILE *file) {
  for (UINTN i=0;i<file->file_size_bytes;i++) {
    CHAR8 c=file->content[i];
    if (c=='\n') {
      Print(L"\r\n");
    } else {
      Print(L"%c",(CHAR16)c);
    }
  }
}
EFI_STATUS bp_console_read_password(CHAR16 *prompt,bp_console_PASSWORD **pwd,CHAR16 hiding_char) {
  EFI_STATUS status;
  if (prompt==NULL || pwd==NULL) {
    return EFI_INVALID_PARAMETER;
  }
  Print(L"%s",prompt);
  EFI_INPUT_KEY key;
  UINTN buf_size=16;
  UINTN length=0;
  CHAR16 *buffer=AllocatePool(buf_size*sizeof(CHAR16));
  if (buffer==NULL) {
    return EFI_OUT_OF_RESOURCES;
  }
  while (TRUE) {
    status=gST->ConIn->ReadKeyStroke(gST->ConIn,&key);
    if (status==EFI_NOT_READY) {
      continue;
    } else if (EFI_ERROR(status)) {
      FreePool(buffer);
      return status;
    }
    if (key.UnicodeChar==CHAR_CARRIAGE_RETURN) {
      break;
    } else if (key.UnicodeChar==CHAR_BACKSPACE) {
      if (length>0) {
        length--;
        Print(L"\b \b");
      }
    } else if (key.UnicodeChar>=L' ' && key.UnicodeChar<=0x7E) {
      if (length+1>=buf_size) {
        CHAR16 *new_buf=AllocatePool(buf_size*2*sizeof(CHAR16));
        if (new_buf==NULL) {
          FreePool(buffer);
          return EFI_OUT_OF_RESOURCES;
        }
        CopyMem(new_buf,buffer,length*sizeof(CHAR16));
        FreePool(buffer);
        buffer=new_buf;
        buf_size*=2;
      }
      buffer[length]=key.UnicodeChar;
      length++;
      if (hiding_char!=0) {
        Print(L"%c",hiding_char);
      } else {
        Print(L"%c",key.UnicodeChar);
      }
    }
  }
  buffer[length]=L'\0';
  *pwd=AllocatePool(sizeof(bp_console_PASSWORD));
  if (*pwd==NULL) {
    FreePool(buffer);
    return EFI_OUT_OF_RESOURCES;
  }
  (*pwd)->password=buffer;
  (*pwd)->size=length;
  Print(L"\n");
  return EFI_SUCCESS;
}
