library(readr)
library (dplyr)

#additional libraries for images stuff
library (magick)
library (data.table)

## create list
seafilefolder= "/Users/colombj/Documents/Seafile/SFB1315info/"
orcidlist1= rorcid::orcid_search(grant_number = 327654276)

people_sfb <- read_delim(paste0(seafilefolder,"sfb1315_people.csv"),
                         "\t", trim_ws = TRUE, skip = 0, na=character())

left_join(orcidlist1, people_sfb, by = c("name" = "artist"))
p_template =  readLines("automation_websiteelementscreation/authors_template.md")


a= as.character("0000-0002-3127-5520")
b=rorcid::orcid_id(a)[[1]]

##---  links
urlname=b$`researcher-urls`$`researcher-url`$`url-name`
url=b$`researcher-urls`$`researcher-url`$url.value



for (i in c(1: nrow(orcidlist))){
  a= as.character("0000-0001-5307-1564")
  # a= as.character(orcidlist[i])
  b=rorcid::orcid_id(a)[[1]]
  
  ## specific
  code = gsub(" ", "-",tolower(paste0(b$name$`given-names`, "-", b$name$`family-name`)))
  
  ## from external sfb list
  role= people_sfb$role_group[people_sfb$people_code == code]
  
  ## usual
  name = paste0(b$name$`given-names`, " ", b$name$`family-name`)
  bio = b$biography$content
  
  ## links
  githublink= url[grepl("github", url)][1]
  twitterlink = url[grepl("twitter", url)][1]
  picturelink = url[grepl("picture", urlname)][1]
  lablink = url[grepl("lab", urlname)][1]
  
  SOCIAL = paste0("- icon: orcid \n  icon_pack: ai \n  link: ",a)
  SOCIAL = paste0("\n- icon: globe \n  icon_pack: fas \n  link: ",lablink)
  SOCIAL = paste0(SOCIAL,"\n- icon: twitter \n  icon_pack: fab \n  link: ",twitterlink)
  SOCIAL = paste0(SOCIAL,"\n- icon: github \n  icon_pack: fab \n  link: ",githublink)
  
  tweetname = substring(twitterlink,21)
  a=rtweet::lookup_users(tweetname)
  HERESHORTBIO = a$description
  
  ## set from template
  
  pdirectory =paste0("content/authors/",code)
  dir.create(pdirectory, recursive = TRUE)
  
  templatenew = p_template
  templatenew =sub ("DISPLAYNAME", name,templatenew)
  templatenew =sub ("USERNAME", code,templatenew)
  templatenew =sub ("HEREROLE", orcidlist$role_group[i],templatenew) ## not an orcid info
  templatenew =sub ("HERESHORTBIO", HERESHORTBIO,templatenew) ## from twitter
  templatenew =sub ("HERESOCIAL", SOCIAL,templatenew)
  templatenew =sub ("HERETEXT", bio,templatenew)
  
  writeLines(templatenew, paste0(pdirectory,"/_index.md") )
  
  # add default avatar image if none present:
  
  
  
  if (!file.exists(paste0(pdirectory,"/avatar.jpg")) && !is.na(picturelink)){
    
    download.file(sub("_normal.", ".",picturelink),paste0(pdirectory,"/avatar.jpg"), mode ="wb")
  }
  if (!file.exists(paste0(pdirectory,"/avatar.jpg"))){
    file.copy ("automation_websiteelementscreation/avatar.jpg",
               paste0(pdirectory,"/avatar.jpg"))
  }
  
  
}

# for tests
#writeLines(templatenew, "test.md" )

