package com.sgrailways.giftidea;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.*;
import android.widget.EditText;
import android.widget.TextView;
import com.google.common.base.Joiner;
import com.google.inject.Inject;
import com.sgrailways.HashTagLocator;
import com.sgrailways.R;
import org.joda.time.DateTime;
import org.joda.time.format.ISODateTimeFormat;
import roboguice.fragment.RoboFragment;
import roboguice.inject.InjectResource;
import roboguice.inject.InjectView;

import java.util.LinkedHashSet;

public class NewIdeaFragment extends RoboFragment {
    @Inject Database database;
    @Inject HashTagLocator hashTagLocator;
    @InjectView(R.id.idea) EditText idea;
    @InjectView(R.id.recipients_view) TextView recipients;
    @InjectView(R.id.hash_tag_count) TextView hashTagCount;
    @InjectView(R.id.gift_ideas_label) TextView giftIdeasLabel;
    @InjectResource(R.string.gift_idea) String giftIdea;
    @InjectResource(R.string.gift_ideas) String giftIdeas;
    @InjectResource(R.string.no_hash_tags_message) String noHashTagsMessage;
    @InjectResource(R.string.no_idea_message) String noIdeaMessage;
    Joiner joiner = Joiner.on(", ");
    boolean hasHashTags = false;
    boolean hasAppropriateLength = false;

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_new_idea, container, false);
    }

    @Override public void onResume() {
        super.onResume();
        idea.addTextChangedListener(new TextWatcher() {
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            public void afterTextChanged(Editable s) {
                LinkedHashSet<String> hashTags = hashTagLocator.findAllIn(s.toString());
                hashTagCount.setText(String.valueOf(hashTags.size()));
                giftIdeasLabel.setText(hashTags.size() == 1 ? giftIdea : giftIdeas);
                hasHashTags = hashTags.size() > 0;
                hasAppropriateLength = hashTagLocator.removeAllFrom(s.toString()).length() > 0;
                recipients.setText(joiner.join(hashTags));
            }
        });
    }

    @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.save, menu);
    }

    @Override public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_create:
                if (!hasHashTags) {
                    idea.setError(noHashTagsMessage);
                } else if (!hasAppropriateLength) {
                    idea.setError(noIdeaMessage);
                } else {
                    String now = DateTime.now().toString(ISODateTimeFormat.basicDateTime());
                    ContentValues ideaValues = new ContentValues();
                    ideaValues.put(Database.IdeasTable.IDEA, hashTagLocator.removeAllFrom(idea.getText().toString()));
                    ideaValues.put(Database.IdeasTable.CREATED_AT, now);
                    ideaValues.put(Database.IdeasTable.UPDATED_AT, now);
                    SQLiteDatabase wdb = database.getWritableDatabase();
                    LinkedHashSet<String> hashTags = hashTagLocator.findAllIn(idea.getText().toString());
                    try {
                        wdb.beginTransaction();
                        for (String hashTag : hashTags) {
                            ContentValues recipientValues = new ContentValues();
                            recipientValues.put(Database.RecipientsTable.NAME, hashTag);
                            recipientValues.put(Database.RecipientsTable.CREATED_AT, now);
                            recipientValues.put(Database.RecipientsTable.UPDATED_AT, now);
                            long recipientId = wdb.insert(Database.RecipientsTable.TABLE_NAME, null, recipientValues);
                            ideaValues.put(Database.IdeasTable.RECIPIENT_ID, recipientId);
                            wdb.insert(Database.IdeasTable.TABLE_NAME, null, ideaValues);
                        }
                        wdb.setTransactionSuccessful();
                    } finally {
                        wdb.endTransaction();
                    }
                    getActivity().finish();
                }
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }
}

@@ -615,16 +615,53 @@
 ectView;
+%0Aimport roboguice.util.SafeAsyncTask;
 %0A%0Aimport
@@ -3028,16 +3028,140 @@
  else %7B%0A
+                    new SafeAsyncTask%3CBoolean%3E() %7B%0A                        public Boolean call() throws Exception %7B%0A        
         
@@ -3257,32 +3257,40 @@
                 
+        
 ContentValues id
@@ -3313,32 +3313,40 @@
 ontentValues();%0A
+        
                 
@@ -3460,32 +3460,40 @@
                 
+        
 ideaValues.put(D
@@ -3541,32 +3541,40 @@
                 
+ 
+       
 ideaValues.put(D
@@ -3630,16 +3630,24 @@
         
+      
+  
 SQLiteDa
@@ -3687,24 +3687,32 @@
 Database();%0A
+        
             
@@ -3829,14 +3829,30 @@
     
+  
-try %7B%0A
+      try %7B%0A        
     
@@ -3919,16 +3919,24 @@
         
+        
 for (Str
@@ -3981,32 +3981,40 @@
                 
+  
+      
 ContentValues re
@@ -4070,32 +4070,40 @@
                 
+       
+ 
 recipientValues.
@@ -4147,16 +4147,24 @@
 shTag);%0A
+        
         
@@ -4266,32 +4266,40 @@
                 
+   
+     
 recipientValues.
@@ -4337,32 +4337,40 @@
 DATED_AT, now);%0A
+        
                 
@@ -4492,32 +4492,40 @@
                 
+        
 ideaValues.put(D
@@ -4595,24 +4595,32 @@
             
+    
+    
 wdb.insert(D
@@ -4685,34 +4685,50 @@
                 
-%7D%0A
+        %7D%0A        
                 
@@ -4763,24 +4763,77 @@
 ccessful();%0A
+                                return true;%0A        
             
@@ -4848,24 +4848,32 @@
 %7D finally %7B%0A
+        
             
@@ -4918,33 +4918,100 @@
                 
-%7D
+        %7D%0A                        %7D%0A                    %7D.execute();
 %0A               

save the data off the ui thread