deleteUnitId :: HasUnitId a
             => UnitId -> PackageIndex a
             -> PackageIndex a
deleteUnitId ipkgid original@(PackageIndex pids pnames) =
  case Map.updateLookupWithKey (\_ _ -> Nothing) ipkgid pids of
    (Nothing,     _)     -> original
    (Just spkgid, pids') -> mkPackageIndex pids'
                                          (deletePkgName spkgid pnames)

  where
    deletePkgName spkgid =
      Map.update (deletePkgVersion spkgid) (packageName spkgid)

    deletePkgVersion spkgid =
        (\m -> if Map.null m then Nothing else Just m)
      . Map.update deletePkgInstance (packageVersion spkgid)

    deletePkgInstance =
        (\xs -> if null xs then Nothing else Just xs)
      . List.deleteBy (\_ pkg -> installedUnitId pkg == ipkgid) undefined

-- | Backwards compatibility wrapper for Cabal pre-1.24.

deleteUnitId :: HasUnitId a
             => UnitId -> PackageIndex a
             -> PackageIndex a
deleteUnitId ipkgid original@(PackageIndex pids pnames) =
  case Map.updateLookupWithKey (\_ _ -> Nothing) ipkgid pids of
    (Nothing,     _)     -> original
    (Just spkgid, pids') -> mkPackageIndex pids'
                                          (deletePkgName spkgid pnames)

  where
    deletePkgName spkgid =
      Map.update (deletePkgVersion spkgid) (packageName spkgid)

    deletePkgVersion spkgid =
        (\m -> if Map.null m then Nothing else Just m)
      . Map.update deletePkgInstance (packageVersion spkgid)

    deletePkgInstance =
        (\xs -> if null xs then Nothing else Just xs)
      . List.deleteBy (\_ pkg -> installedUnitId pkg == ipkgid) undefined

-- | Backwards compatibility wrapper for Cabal pre-1.24.

deleteUnitId ipkgid original@(PackageIndex pids pnames) =
  case Map.updateLookupWithKey (\_ _ -> Nothing) ipkgid pids of
    (Nothing,     _)     -> original
    (Just spkgid, pids') -> mkPackageIndex pids'
                                          (deletePkgName spkgid pnames)

  where
    deletePkgName spkgid =
      Map.update (deletePkgVersion spkgid) (packageName spkgid)

    deletePkgVersion spkgid =
        (\m -> if Map.null m then Nothing else Just m)
      . Map.update deletePkgInstance (packageVersion spkgid)

    deletePkgInstance =
        (\xs -> if null xs then Nothing else Just xs)
      . List.deleteBy (\_ pkg -> installedUnitId pkg == ipkgid) undefined

-- | Backwards compatibility wrapper for Cabal pre-1.24.
