package com.crossbowffs.quotelock.modules.wikiquote;

import android.content.ComponentName;
import android.content.Context;

import com.crossbowffs.quotelock.R;
import com.crossbowffs.quotelock.api.QuoteData;
import com.crossbowffs.quotelock.api.QuoteModule;
import com.crossbowffs.quotelock.utils.IOUtils;
import com.crossbowffs.quotelock.utils.Xlog;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WikiquoteQuoteModule implements QuoteModule {
    private static final String TAG = WikiquoteQuoteModule.class.getSimpleName();

    @Override
    public String getDisplayName(Context context) {
        return context.getString(R.string.module_wikiquote_name);
    }

    @Override
    public ComponentName getConfigActivity(Context context) {
        return null;
    }

    @Override
    public int getMinimumRefreshInterval(Context context) {
        return 86400;
    }

    @Override
    public QuoteData getQuote(Context context) throws IOException {
        String quotePage = IOUtils.downloadString("https://zh.m.wikiquote.org/zh-cn/Wikiquote:%E9%A6%96%E9%A1%B5");

        Matcher quoteAllTextMatcher = Pattern.compile("(?<=<td>).*?(?=</td>)").matcher(quotePage);
        if (!quoteAllTextMatcher.find()) {
            Xlog.e(TAG, "Failed to parse quote data");
            return null;
        }
        String quoteAllText = quoteAllTextMatcher.group(0).replaceAll("<.*?>", "");

        Matcher quoteTextMatcher = Pattern.compile("^.*?(?=(\\s|)(——|--|──))").matcher(quoteAllText);
        if (!quoteTextMatcher.find()) {
            Xlog.e(TAG, "Failed to parse quote text");
            return null;
        }

        Matcher quoteSourceMatcher = Pattern.compile("(?<=(——|--|──)\\s).*?$").matcher(quoteAllText);
        if (!quoteSourceMatcher.find()) {
            Xlog.e(TAG, "Failed to parse quote source");
            return null;
        }

        String quoteText = quoteTextMatcher.group(0);
        String quoteSource = String.format("―%s", quoteSourceMatcher.group(0));
        return new QuoteData(quoteText, quoteSource);
    }
}

@@ -1460,28 +1460,24 @@
 atcher quote
-Text
 Matcher = Pa
@@ -1492,22 +1492,21 @@
 mpile(%22%5E
+(
 .*?
-(?=
+)
 (%5C%5Cs%7C)(%E2%80%94
@@ -1517,241 +1517,19 @@
 %7C%E2%94%80%E2%94%80)
-)%22).matcher(quoteAllText);%0A        if (!quoteTextMatcher.find()) %7B%0A            Xlog.e(TAG, %22Failed to parse quote text%22);%0A            return null;%0A        %7D%0A%0A        Matcher quoteSourceMatcher = Pattern.compile(%22(?%3C=(%E2%80%94%E2%80%94%7C--%7C%E2%94%80%E2%94%80)%5C%5Cs)
+(%5C%5Cs%7C)(
 .*?
+)
 $%22).
@@ -1565,30 +1565,24 @@
   if (!quote
-Source
 Matcher.find
@@ -1638,14 +1638,12 @@
 ote 
-source
+text
 %22);%0A
@@ -1710,20 +1710,16 @@
  = quote
-Text
 Matcher.
@@ -1724,17 +1724,17 @@
 r.group(
-0
+1
 );%0A     
@@ -1783,22 +1783,16 @@
 %22, quote
-Source
 Matcher.
@@ -1797,17 +1797,17 @@
 r.group(
-0
+5
 ));%0A    

Optimized the regex code of Wikiquote