on run {input, parameters}

say "Demon started."
set connect_check_success_count to 0
set state to 0 -- 0:normal, 1:error, 2:error_to_normal
repeat
delay 10
try
do shell script "ping -c 1 -W 3000 youtube.com"
if connect_check_success_count = 0 then
copy connect_check_success_count + 1 to connect_check_success_count
say "Connected."
else if connect_check_success_count > 0 and state = 2 then
copy 0 to state
say "Reconnected."
end if

on error
set error_count to 1
repeat
try

do shell script "ping -c 1 -W 3000 youtube.com"

exit repeat

on error

copy error_count + 1 to error_count

if error_count = 3 then
exit repeat
end if
delay 5
end try
end repeat

if error_count = 3 then
copy 1 to state
beep

say "Connection error! Try reconnect..."
tell application "System Events"
tell network preferences
disconnect service "jp"
connect service "jp"
end tell
end tell

copy 2 to state
end if

end try
end repeat

return input

end run