{-# OPTIONS_GHC -fno-warn-orphans #-}
{-# LANGUAGE OverloadedStrings #-}

{- Copyright 2016 Joey Hess <id@joeyh.name>
 -
 - Licensed under the GNU AGPL version 3 or higher.
 -}

module Serialization where

import Types
import Raaz.Core.Encode
import qualified Data.ByteString as B
import qualified Data.ByteString.UTF8 as BU8
import qualified Data.Text as T
import Data.Word

-- | A SecretKeySource is serialized in the form "keytype value".
-- For example "gpg C910D9222512E3C7", or "file path".
instance Encodable SecretKeySource where
	toByteString (GpgKey (KeyId b)) =
		"gpg" <> B.singleton sepChar <> BU8.fromString (T.unpack b)
	toByteString (KeyFile f) =
		"file" <> B.singleton sepChar <> BU8.fromString f
	fromByteString b = case B.break (== sepChar) b of
		(t, rest)
			| B.null rest -> Nothing
			| otherwise -> 
				let i = B.drop 1 rest
				in case t of
					"gpg" -> Just $ GpgKey (KeyId (T.pack (BU8.toString i)))
					"file" -> Just $ KeyFile (BU8.toString i)
					_ -> Nothing

instance Encodable Name where
	toByteString (Name n) = n
	fromByteString = Just . Name

instance Encodable StorableObjectIdent where
	toByteString (StorableObjectIdent i) = i
	fromByteString = Just . StorableObjectIdent

instance Encodable StorableObject where
	 toByteString (StorableObject b) = b
	 fromByteString = Just . StorableObject

-- | A share is serialized without its share number. This prevents
-- an attacker from partitioning their shares by share number.
instance Encodable Share where
	toByteString (Share _n o) = toByteString o
	fromByteString _ = Nothing

sepChar :: Word8
sepChar = 32
