module ByteStrHelpers where

import Data.Bits
import Char
import Numeric

byteStrToHex challenge =
    hexDump (byteStrToInt challenge)

byteStrToInt :: String -> Integer
byteStrToInt string =
    -- thanks dons @ #haskell
    -- here is how the code would look like if I actually knew Haskell better
    -- so be happy I don't ;-)
    foldr (\b a -> a `shiftL` 8 .|. fromIntegral b) 0 (map ord string)

evenLength string =
    if length string `mod` 2 == 0
        then string
        else "0" ++ string

clearColons "" = ""
clearColons (':' : xs) = clearColons xs
clearColons (x : xs) = x : clearColons xs
    
hexStrToInt :: String -> Integer
hexStrToInt "" = 0 :: Integer
hexStrToInt string =
    lowerByte string + (hexStrToInt $ (init . init) string) `shiftL` 8

lowerByte string =
    read $ "0x" ++ [lastButOneChar string, lastChar string] :: Integer

lastButOneChar string =
    head $ drop 1 (reverse string)

lastChar string =
    head (reverse string)

    -- lower_byte -- + next_res --  `shiftL` 8
    -- let next_res = hexStrToInt ((init . init) string) :: Integer
    
-- this is how it looks if I do it, probably horribly inefficient, though :)
intToByteStr :: Integer -> String
intToByteStr number =
    if number < 256
        then [chr (read (show number))]
        else (intToByteStr (number `shiftR` 8)) ++ (intToByteStr (number .&. 255)) 

hexDump 0 = "00"
hexDump number =
    if number < 256
        then myShowHex number
        else (hexDump (number `shiftR` 8)) ++ ":" ++ (hexDump (number .&. 255))

myShowHex number = do
    let hexstr = showHex number ""
    if length hexstr == 1
        then "0" ++ hexstr
        else hexstr
