package jp.gecko655.bot.fujimiya;


import java.text.DateFormat;
import java.util.List;
import java.util.TimeZone;
import java.util.logging.Level;
import java.util.regex.Pattern;

import jp.gecko655.bot.AbstractCron;
import jp.gecko655.bot.DBConnection;
import twitter4j.Paging;
import twitter4j.Relationship;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.TwitterException;

public class FujimiyaReply extends AbstractCron {
    
    static final DateFormat format = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.FULL);
    private static final Pattern keishouPattern = Pattern.compile("(くん|さん|君|ちゃん)$");
    private static final Pattern whoPattern = Pattern.compile("( 誰$| だれ$|誰[^だで]|だれ[^だで]|誰だ[^と]?|だれだ[^と]?| 違う| ちがう)");

    public FujimiyaReply() {
        format.setTimeZone(TimeZone.getDefault());
    }

    @Override
    protected void twitterCron() {
        try {
            List<Status> replies = twitter.getMentionsTimeline((new Paging()).count(20));
            if(replies.isEmpty()){
                logger.log(Level.INFO, "Not yet replied. Stop.");
                return;
            }
            DBConnection.setLastStatus(replies.get(0));
            Status lastStatus = DBConnection.getLastStatus();
             if(lastStatus == null){
                 logger.log(Level.INFO,"memcache saved. Stop. "+replies.get(0).getUser().getName()+"'s tweet at "+format.format(replies.get(0).getCreatedAt()));
                 return;
             }
            
            for(Status reply : replies){
                if(isOutOfDate(reply, lastStatus))
                    break;
                Relationship relation = twitter.friendsFollowers().showFriendship(twitter.getId(), reply.getUser().getId());
                
                if(!relation.isSourceFollowingTarget()){
                    followBack(reply);
                }else if(whoPattern.matcher(reply.getText()).find()){
                    // put latest image URL to black-list
                    who(reply);    
                }else{
                    //auto reply (when fujimiya-san follows the replier)
                    StatusUpdate update= new StatusUpdate("@"+reply.getUser().getScreenName()+" ");
                    update.setInReplyToStatusId(reply.getId());
                    if(((int) (Math.random()*10))==1){//10%
                        updateStatusWithMedia(update, "山岸沙希 かわいい 一週間フレンズ。", 100);
                    }else{
                        updateStatusWithMedia(update, "藤宮香織 かわいい 一週間フレンズ。",100);
                    }
                }
            }
        } catch (TwitterException e) {
            logger.log(Level.WARNING,e.toString());
            e.printStackTrace();
        }
    }

    private boolean isOutOfDate(Status reply, Status lastStatus) {
        if(reply.getCreatedAt().getTime()-lastStatus.getCreatedAt().getTime()<=0){
            logger.log(Level.INFO, reply.getUser().getName()+"'s tweet at "+format.format(reply.getCreatedAt()) +" is out of date");
            return true;
        }
        return false;
    }

    private void followBack(Status reply) throws TwitterException {
        twitter.createFriendship(reply.getUser().getId());
        String userName = reply.getUser().getName();
        if(!keishouPattern.matcher(userName).find()){
            userName = userName + "くん";
        }
        StatusUpdate update= new StatusUpdate("@"+reply.getUser().getScreenName()+" もしかして、あなたが"+userName+"？");
        update.setInReplyToStatusId(reply.getId());
        twitter.updateStatus(update);
    }

    private void who(Status reply) {
        //Store the url to the black list.
        DBConnection.storeImageUrlToBlackList(reply.getInReplyToStatusId(),reply.getUser().getScreenName());

        try{
            //Delete the reported tweet.
            twitter.destroyStatus(reply.getInReplyToStatusId());
            
            //Apologize to the report user.
            StatusUpdate update= new StatusUpdate("@"+reply.getUser().getScreenName()+" 間違えちゃった。ごめんね！");
            update.setInReplyToStatusId(reply.getId());
            twitter.updateStatus(update);
        }catch(TwitterException e){
            e.printStackTrace();
        }
    }
}

@@ -171,16 +171,52 @@
 Pattern;
+%0Aimport java.util.stream.Collectors;
 %0A%0Aimport
@@ -943,16 +943,78 @@
   try %7B%0A
+            Status lastStatus = DBConnection.getLastStatus();%0A
         
@@ -1093,16 +1093,124 @@
 unt(20))
+%0A                    .stream().filter(reply -%3E !isOutOfDate(reply, lastStatus)).collect(Collectors.toList())
 ;%0A      
@@ -1271,20 +1271,20 @@
 g(Level.
+F
 IN
-FO
+E
 , %22Not y
@@ -1402,70 +1402,8 @@
 ));%0A
-            Status lastStatus = DBConnection.getLastStatus();%0A
     
@@ -1694,86 +1694,8 @@
 s)%7B%0A
-                if(isOutOfDate(reply, lastStatus))%0A                    break;%0A
     
@@ -2871,24 +2871,71 @@
 %0A        if(
+lastStatus==null) return false;%0A        return 
 reply.getCre
@@ -2947,18 +2947,15 @@
 t().
-getTime()-
+before(
 last
@@ -2979,212 +2979,82 @@
 At()
-.getTime()%3C=0)%7B%0A            logger.log(Level.INFO, reply.getUser().getName()+%22's tweet at %22+format.format(reply.getCreatedAt()) +%22 is out of date%22);%0A            return true;%0A        %7D%0A        return false
+)%0A                %7C%7Creply.getCreatedAt().equals(lastStatus.getCreatedAt())
 ;%0A  

Set "Not yet replied" message Level.FINE.