package com.hyperling.apps.wheretheriverfrowns;

import android.content.Context;
import android.graphics.Color;
import android.util.Log;
import android.widget.LinearLayout;
import android.widget.TextView;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

/**
 * Created by ling on 9/24/16.
 */

public class WebPage {
    private Context context;

    private String link;
    private String html = "";

    private int index;

    private ArrayList<String> titles;
    private ArrayList<String> links;
    private ArrayList<String> dates;

    private LinearLayout content;

    private boolean DEBUG = false;
    private String TAG;

    public WebPage(Context context, String link) {
        TAG = context.getResources().getString(R.string.TAG);

        this.context = context;
        this.link = link;
        URL url;
        InputStream is = null;
        BufferedReader br;
        String line;

        titles = new ArrayList<>();
        links = new ArrayList<>();
        dates = new ArrayList<>();

        try {
            url = new URL(link);
            is = url.openStream();  // throws an IOException
            br = new BufferedReader(new InputStreamReader(is));

            while ((line = br.readLine()) != null) {
                html = html.concat(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) is.close();
            } catch (IOException ioe) {
                // nothing to see here
            }
        }

        if (html.length() > 0) {
            html = html.replace("&quot;", "\"");

            int nextArticle;
            index = 0;
            while (findArticle() > 0) {
                // Move to the next article
                nextArticle = findArticle();
                html = html.substring(nextArticle);

                // Get the url
                html = html.substring(html.indexOf("href=") + 6);
                String articleLink = html.substring(0, html.indexOf('\"'));
                links.add(index, articleLink);

                // Get the title
                html = html.substring(html.indexOf('>') + 1);
                String articleTitle = html.substring(0, html.indexOf("</a>"));
                articleTitle = removeSpaces(articleTitle);
                titles.add(index, articleTitle);

                // Get the date
                /* Date looks like:
                <p class="blog-date">
                    <span class="date-text">9/21/2016</span>
                </p>
                 */
                html = html.substring(html.indexOf("<p class=\"blog-date\">"));
                html = html.substring(html.indexOf('>') + 1);
                html = html.substring(html.indexOf('>') + 1);
                String articleDate = html.substring(0, html.indexOf("</span>"));
                articleDate = removeSpaces(articleDate);
                dates.add(index, articleDate);

                index += 1;
            }

            if (context != null) {
                if (index == 1) {
                    // Page is an article, get text
                /* Text starts at:
                <div class="blog-content">
                 */
                    content = new LinearLayout(context);
                    content.setOrientation(LinearLayout.VERTICAL);

                    html = html.substring(html.indexOf("<div class=\"blog-content\">"));
                    html = html.substring(html.indexOf('>') + 1);

                    if (DEBUG) Log.d(TAG, "DEBUG: WebPage:  html=" + html);

                    int level = 1;
                    String contentText = "";
                    while (level > 0) {
                    /*
                    Paragraphs looks like:
                    <div class="paragraph">

                    New TextViews at:
                    <br></br>

                    level += 1 at <
                    level -= 2 at </

                    Otherwise just grab everything between ><
                    */

                        while (html.indexOf('&') < html.indexOf('<')) {
                            contentText = contentText.concat(html.substring(0, html.indexOf('&')));
                            html = html.substring(html.indexOf(';') + 1);
                        }

                        contentText = contentText.concat(html.substring(0, html.indexOf('<')));
                        contentText = removeSpaces(contentText);


                        html = html.substring(html.indexOf('<'));

                        // TODO: Testing only
                        if (level > 0) {
                            //System.out.println("DEBUG:  level=" + level + " html=" + html);
                            //System.out.println("DEBUG:  contentText=" + contentText);
                        }

                        if (html.indexOf("<div class=\"paragraph\">") == 0) {

                            TextView newView = new TextView(context);
                            newView.setText(contentText);
                            newView.setTextColor(Color.BLACK);
                            content.addView(newView);

                            contentText = "";
                        } else if (html.indexOf("<br>") == 0 || html.indexOf("<br />") == 0) {
                            contentText = contentText.concat("\n");
                            level -= 1;
                        } else if (html.indexOf("<meta ") == 0) {
                            level -= 1;
                        } else if (html.indexOf("<img ") == 0) {
                            level -= 1;
                        } else if (html.indexOf("<!--") == 0) {
                            level -= 1;
                        } else if (html.indexOf("</") == 0) {
                            level -= 2;
                        }

                        if (html.indexOf("/>") < html.indexOf(">")) {
                            level -= 1;
                        }

                        html = html.substring(html.indexOf('>') + 1);
                        level += 1;
                    }

                    TextView newView = new TextView(context);
                    newView.setText(contentText);
                    newView.setTextColor(Color.BLACK);
                    content.addView(newView);
                }
            }
        }
    }

    private int findArticle(){
        /* Example of an article title:
        <a class="blog-title-link blog-link" href="http://www.wheretheriverfrowns.com/all-stories/kite-line-september-16-2016-national-prison-strike-updates">Kite Line – September 16, 2016: National Prison Strike Updates</a>
         */
        return html.indexOf("<a class=\"blog-title-link blog-link\"");
    }

    // TODO: Testing only
    public String getHTML(){
        return html;
    }
    public String getLink(){
        return link;
    }

    public ArrayList<String> getTitles(){
        return titles;
    }

    public ArrayList<String> getLinks(){
        return links;
    }

    public ArrayList<String> getDates(){
        return dates;
    }

    public LinearLayout getContent(){
        return content;
    }

    private String removeSpaces(String string){
        while(string.contains("  ")) {
            string = string.replace("  ", " ");
        }
        //string = string.replace("\n", "");
        string = string.replace("\t", "");
        return string;
    }

    public void setDEBUG(boolean debug){
        this.DEBUG = debug;
    }
}
