#!/bin/bash

timestamp(){
  echo $((${EPOCHREALTIME//.} / 1000))
}

_get_pixel_color(){
  # old version that takes up to .5s to run
  START=$(timestamp)
  x=$1;
  y=$2;
  output_path="/tmp/$(mktemp -u XXXXXX).png"
  scrot "$output_path"
  magick "$output_path" -format "%[hex:p{$x,$y}]" info:
  END=$(timestamp)
  DIFF=$(echo "$END - $START" | bc)
  echo "{\"getting_pixel_color_took\": \"${DIFF}ms\"}" > /dev/stderr
}


get_pixel_color(){
  x=$1;
  y=$2;
  FIREFOX_ID=$(wmctrl -lp | grep Firefox | awk '{print $1}')
  if [ "$FIREFOX_ID" = "" ]
  then
    echo "NONE"
    return
  fi
  grabc -w "$FIREFOX_ID" -l +${x}+${y}
}


extract_text(){
  output_path="/tmp/$(mktemp -u XXXXXX).png"
  cropped_path=$output_path--cropped.png
  scrot $output_path
  left=$1
  top=$2
  width=$3
  height=$4
  # https://www.libvips.org/API/current/libvips-conversion.html#vips-extract-area
  vips extract_area "$output_path" "$cropped_path" $left $top $width $height
  tesseract "$cropped_path" stdout -l eng
}

click (){
  xdotool mousemove $1 $2
  xdotool click 1
}

grab_no=0

grab(){
  NOTE="$grab_no $@"
  #echo $@
  ((grab_no++))
  # scrot --note "-f '/usr/share/fonts/noto/NotoSansMono-Medium.ttf/40' -c 255,0,0,255 -t '$NOTE'" "/opt/static/$(date -Iminutes).png"
  #echo "not grabbing"
}

quicktype(){
  echo "$1" | xclip -sel clip
  keycombo Control_L v
}

grab_screen_to_public(){
  id=$1
  format="jpg"
  filepath="/opt/static/$id/preview.$format"
  tempfile="/opt/static/$id/temp.$format"
  croppedfile="/opt/static/$id/temp-cropped.$format"
  scaledfile="/opt/static/$id/temp-cropped-scaled.$format"
  mkdir -p "/opt/static/$id"
  rm -f "$tempfile"
  scrot "$tempfile"
  vips crop "$tempfile" "$croppedfile" 0 24 2856 1564
  vips resize "$croppedfile" "$scaledfile" 0.1
  mv -f "$scaledfile" "$filepath"
}

keycombo(){
  for key in "$@"
  do
    xdotool keydown $key
    sleep 0.01
  done
  for key in "$@"
  do
    xdotool keyup $key
    sleep 0.01
  done
  sleep 0.05
}



start_firefox(){
    rm -rf /root/.mozilla/firefox/bifup8k5.docker/sessionstore-backups
    #echo 'user_pref("layout.css.devPixelsPerPx", "1.5");' >> /root/.mozilla/firefox/bifup8k5.docker/prefs.js
    firefox --devtools > /dev/null &
    FIREFOX_PID=$!
    while [ $(get_pixel_color 100 100) = "NONE" ]
    do
      sleep 0.1
    done;
}

prepare_firefox(){
#  xdotool key Return # in case there's a "firefox closed unexpectedly" button
#  sleep 1
#  grab "after sleep 1"
  click 1886 13 #maximize button
  grab "after maximize"
  FIREFOX_WIDTH=$(wmctrl -lpG | grep Firefox | awk '{print $6}')
  while [ "$FIREFOX_WIDTH" != "2880" ]
  do
    sleep 0.1
  done
  #grab "after sleep 1"
  # no need to reopen the network tab, as it's almost certainly already open
  # keycombo Control_L Shift_L e
  # grab "after ctrl+shift+e"
  # keycombo Shift_L F5 #profiler
  # grab "after shift-c F5"
  # keycombo Control_L Shift_L e
  # sleep 5 # it needs some time
}


wait_for_pixel_color(){
  x=$1;
  y=$2;
  color=$3;
  timeout=$4;
  start=$(timestamp)
  while [ $(get_pixel_color 143 122) != "$color" ]
  do
    sleep 0.1
    ts=$(timestamp)
    if [ $(( ts - start )) -gt $(( timeout * 1000 )) ]
    then
      return
    fi
  done
}

wait_for_website_to_load(){
  times=0
  while [ $(get_pixel_color 143 122) = "#2e3436" ] # the center of the X icon that becomes a "refresh" icon once the website is finished loading
  do
    sleep 0.5
    #printf "."
    #scrot
    times=$((times + 1))
    if [ $times -eq 30 ]
    then
      echo "{\"current_action\": \"website load timeout, proceeding anyway...\"}"
      break;
    fi
  done
}

load_website(){
  WEBSITE_URL=$1
  WEBSITE_NAME=$2
  keycombo Control_L l
  grab ctrl+l
  quicktype "$WEBSITE_URL"
  grab type url
  xdotool key Delete
  xdotool key Return
  grab enter
  sleep 1
  echo "{\"current_action\": \"Wczytywanie strony $WEBSITE_NAME...\"}"
  wait_for_website_to_load
  sleep 0.3
  wait_for_website_to_load
  sleep 0.3
  wait_for_website_to_load
}

open_network_inspector(){
  keycombo Shift_L F5 #profiler
  sleep 0.1
  keycombo Control_L Shift_L e
  wait_for_pixel_color 1777 152 0a84ff 3
}

open_console(){
  keycombo Shift_L F5 #profiler
  sleep 0.1
  keycombo Control_L Shift_L k
  wait_for_pixel_color 1510 152 0a84ff 3
}

network_inspector_search(){
  query=$1
  keycombo Control_L f
  sleep 0.2
  keycombo Control_L a
  sleep 0.1
  xdotool type "$query" 
  #xdotool key Escape
  sleep 0.3
  seq 28 | xargs -I {} xdotool key Tab
  xdotool key Down
  sleep 0.1
  xdotool key Up
  sleep 0.1
}

network_inspector_has_more_entries(){
  grab network_inspector_has_more_entries
  [ $(get_pixel_color 1267 1572) = "#f9f9fa" ]
}

network_inspector_next_entry(){
  xdotool key Tab
  sleep 0.05
  xdotool key Down
  sleep 0.5 # some time is needed here for request headers to render into view
}

# last_message="_____"

# measure(){
  
# }
network_inspector_headers_need_scrolling (){
  color=$(get_pixel_color 2870 1573)
  [ "$color" = "#ededf0" ]
}

screenshot_and_annotate(){
  ID=$1
  index=$2
  DOMAIN=$3
  ORIGIN_DOMAIN=$4
  filename="$ID/${index}.png"
  scrot "/opt/static/$filename"
  grab "searching $DOMAIN"
  BASE_URL="$BASE_URL" python annotate_header.py "$filename" "$DOMAIN" \
      "set-cookie" "identyfikator internetowy z cookie" 11 ""\
      "Cookie" "identyfikator internetowy z cookie" 11 ""\
      "Referer" "Część mojej historii przeglądania" 0 "$ORIGIN_DOMAIN"
}

get_http_status(){
  _url="$1"
  curl --connect-timeout 3 --location --silent --output /dev/null --head --write-out "%{http_code}" "$_url"
}

is_http_error(){
  _url="$1"
  status=$(get_http_status "$_url")
  [ "${status:0:1}" = "4" ] || [ "${status:0:1}" = "0" ]
}
