{-# LANGUAGE Arrows, NoMonomorphismRestriction #-}
import ShadowLibrary.Core

import Text.XML.HXT.Core
import Text.XML.HXT.XPath
-- import Text.XML.HXT.Curl
import Data.List
import Data.List.Utils (replace)

import Text.Regex.Posix
import Text.Printf



extractRecords = extractLinksWithText "//a[@class='title']"  
                 >>> second (arr $ replace "\n\t\t\t\t\t" "")
                 >>> first (extractLinksWithText "//div[@class='title']" 
                     >>> first (extractLinksWithText"//a[@class='obj_galley_link pdf']"))
                     -- >>> first (extractLinksWithText"//ul[@class='value galleys_links']//a[@class='obj_galley_link pdf']"))      	         
-- ... a tutaj te trójki przerabiamy do docelowej struktury ShadowItem

toShadowItem :: (((String, String), String),String)-> ShadowItem
-- toShadowItem :: ((String, String),String) -> ShadowItem
-- toShadowItem ((url, articleTitle), yearlyTitle) =
toShadowItem (((url, articleTitle),pdfTitle), yearlyTitle)=
  (defaultShadowItem url title) {
    originalDate = Just date,
    itype = "periodical",
   format = Just "pdf",
    finalUrl = url
    }

   where title =  replace "\n\t\t\t" "   " yearlyTitle ++ (replace "\t\n\t" "" (replace "\n\n\t" " " articleTitle)) ++ (replace "\n\t\t \n\t\t\t" "     " (replace "\n\t\t\t\t\t \n\t" "" (replace "\n\t\t\t\t\t\t\t \n\t\t\t\t\t" " " (replace "\n\t\t\t\t " ""pdfTitle))))
         date = getDate yearlyTitle
getDate yearlyTitle =
  case yearlyTitle =~~ "(19[0-9][0-9]|20[0-9][0-9])" :: Maybe [[String]] of
    Just [[_, year]] -> year
    otherwise -> error $ "unexpected yearlyTitle " ++ yearlyTitle


main = do
    let start = "https://etyka.uw.edu.pl/index.php/etyka/issue/archive"
    let start2 = "https://etyka.uw.edu.pl/index.php/etyka/issue/archive/2"
    let start3 = "https://etyka.uw.edu.pl/index.php/etyka/issue/archive/3"
    let shadowLibrary = ShadowLibrary {logoUrl=Nothing,
                                       lname="Tom",
                                       abbrev="Etyka",
                                       lLevel=0,
                                       webpage=start}
    extractItemsStartingFromUrl shadowLibrary start (extractRecords >>> arr toShadowItem)
    extractItemsStartingFromUrl shadowLibrary start2 (extractRecords >>> arr toShadowItem)
    extractItemsStartingFromUrl shadowLibrary start3 (extractRecords >>> arr toShadowItem)