package net.mabako.steamgifts.tasks;

import android.os.AsyncTask;
import android.util.Log;

import net.mabako.steamgifts.data.DiscussionExtras;
import net.mabako.steamgifts.data.GiveawayExtras;
import net.mabako.steamgifts.fragments.DiscussionDetailFragment;
import net.mabako.steamgifts.web.WebUserData;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;

public class LoadDiscussionDetailsTask extends AsyncTask<Void, Void, DiscussionExtras> {
    private static final String TAG = LoadDiscussionDetailsTask.class.getSimpleName();

    private final DiscussionDetailFragment fragment;
    private final String discussionId;
    private final int page;

    public LoadDiscussionDetailsTask(DiscussionDetailFragment fragment, String discussionId, int page) {
        this.fragment = fragment;
        this.discussionId = discussionId;
        this.page = page;

    }

    @Override
    protected DiscussionExtras doInBackground(Void... params) {
        String url = "http://www.steamgifts.com/discussion/" + discussionId + "/search?page=" + page;
        Log.d(TAG, "Fetching discussion details for " + url);

        try {
            Connection jsoup = Jsoup.connect(url);
            if (WebUserData.getCurrent().isLoggedIn())
                jsoup.cookie("PHPSESSID", WebUserData.getCurrent().getSessionId());
            Document document = jsoup.get();

            // Update user details
            WebUserData.extract(document);

            DiscussionExtras extras = new DiscussionExtras();

            // Load the description
            Element description = document.select(".comment__display-state .markdown").first();
            if (description != null) // This will be null if no description is given.
                extras.setDescription(description.html());

            // Load comments
            Element rootCommentNode = document.select(".comments").last();
            if (rootCommentNode != null)
                Utils.loadComments(rootCommentNode, extras);

            return extras;
        } catch (IOException e) {
            Log.e(TAG, "Error fetching URL", e);
            return null;
        }
    }

    @Override
    protected void onPostExecute(DiscussionExtras discussionExtras) {
        super.onPostExecute(discussionExtras);
        fragment.addDetails(discussionExtras, page);
    }
}

@@ -417,16 +417,50 @@
 Element;
+%0Aimport org.jsoup.select.Elements;
 %0A%0Aimport
@@ -1960,20 +1960,18 @@
 ment
- rootC
+s c
 omment
+s
 Node
@@ -2001,16 +2001,115 @@
 mments%22)
+;%0A            if (commentsNode.size() %3E 1) %7B%0A                Element rootCommentNode = commentsNode
 .last();
@@ -2105,24 +2105,28 @@
 ode.last();%0A
+    
             
@@ -2170,16 +2170,20 @@
         
+  
+  
 Utils.lo
@@ -2218,16 +2218,30 @@
 extras);
+%0A            %7D
 %0A%0A      

fix for discussions with no comments