# -*- coding: utf-8 -*-
import os
import codecs
import re
import utils
from flask import Flask, jsonify
from flask_cors import CORS
import requests
try:
    from HTMLParser import HTMLParser
except ImportError:
    from html.parser import HTMLParser
try:
    import flask_restx as fl
except ImportError:
    import flask_restplus as fl
Api = fl.Api
Resource = fl.Resource
reqparse = fl.reqparse


# Start Flask app.
app = Flask(__name__)
app.config['JSON_AS_ASCII'] = False
# Show request duration.
app.config.SWAGGER_UI_REQUEST_DURATION = True
CORS(app)
apiversion = 'v0.0.1'
api = Api(app, version=apiversion, title=u'Sanskrit-kosha API', description='Provides APIs to Sanskrit-kosha.')


def preprocess(text):
    """Gives query friendly string."""
    text = text.rstrip('HM')  # SamBuH -> SamBu
    text = re.sub('[aAiIuUfFxXeEoO]$', '', text)  # pAragata -> pAragat
    text = re.sub('^[aAiIuUfFxXeEoO]', '', text)  # azwaka -> zwaka
    text = re.sub('a[tsn]$', '', text)  # Bagavat -> Bagav, Sreyas -> Srey, suDarman -> suDarm
    text = re.sub('in$', '', text)  # kevalin -> keval
    text = re.sub('[td]$', '', text)  # tIrTakft -> tIrTakf (to handle t/d conversion issues)
    print(text)
    return text


def search_in_dict(query, code):
    # ENSK -> ekaksharanamamala_sadhukalashagani
    fullName = utils.code_to_dict(code)
    # ekaksharanamamala, sadhukalashagani
    bookName, author = fullName.split('_')
    #storagedir = os.path.join('var', 'www', 'html', 'kosha.sanskritworld.in')
    #storagedir = os.path.join('/home', 'create', 'Documents', 'projects', 'kosha-trial')
    fin = codecs.open(os.path.join('/var', 'www', 'html', 'kosha.sanskritworld.in', 'data', fullName, 'slp', bookName + '.txt'), 'r', 'utf-8')
    # Read the .txt file
    dictslp = utils.dictcodes_slp[code]
    result = []
    verseDetails = utils.VerseInfo()
    verse = ''
    writeVerse = False
    for lin in fin:
        if lin.startswith(';'):
            (tag, value) = utils.extract_tag(lin)
            if tag == 'p':
                verseDetails.update_pageNum(value)
            if tag == 'k':
                verseDetails.update_kanda(value)
            if tag == 'v':
                verseDetails.update_varga(value)
            if tag == 'vv':
                verseDetails.update_subvarga(value)
        elif re.search('^[$#<]', lin):
            pass
        else:
            verse += lin
            if query in lin:
                writeVerse = True
            if '..' in lin:
                verseDetails.update_verseNum(verse)
                if writeVerse:
                    page = verseDetails.give_page_details()
                    kanda = verseDetails.kanda
                    varga = verseDetails.varga
                    adhyaya = verseDetails.subvarga
                    versenum = verseDetails.verseNum
                    result.append({'verse': verse, 'page': page, 'versenum': versenum, 'kanda': kanda, 'varga': varga, 'adhyaya': adhyaya, 'dictionary': dictslp})
                writeVerse = False
                verse = ''
    return result


def search_in_all(query):
    output = {}
    dictcodes = utils.workingdicts
    for code, fullname in dictcodes.items():
        result = search_in_dict(query, code)
        if len(result) > 0:
            output[code] = result
    return output


@api.route('/' + apiversion + '/dictcode')
class DC(Resource):
    """Return the dictcode and full form of all dictionaries."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self):
        result = utils.workingdicts
        return jsonify(result)


@api.route('/' + apiversion + '/query/<string:query>')
@api.doc(params={'query': 'Word to search.'})
class QD(Resource):
    """Return result for given query in all koshas."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self, query):
        result = search_in_all(query)
        return jsonify(result)


@api.route('/' + apiversion + '/query/<string:query>/koshas/<string:kosha>')
@api.doc(params={'query': 'Word to search.', 'kosha': 'Dictionary code.'})
class QD(Resource):
    """Return result for given query in given dictionary."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self, query, kosha):
        result = search_in_dict(query, kosha)
        return jsonify({kosha: result})


@api.route('/' + apiversion + '/query/<string:query>')
@api.doc(params={'query': 'Word to search.'})
class QD(Resource):
    """Return result for given query in all koshas."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self, query):
        result = search_in_all(query)
        return jsonify(result)


@api.route('/' + apiversion + '/query/<string:query>/koshas/<string:kosha>')
@api.doc(params={'query': 'Word to search.', 'kosha': 'Dictionary code.'})
class QD(Resource):
    """Return result for given query in given dictionary."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self, query, kosha):
        result = search_in_dict(query, kosha)
        return jsonify({kosha: result})


@api.route('/' + apiversion + '/cologne/suggests/<string:term>/<string:kosha>/<string:intran>')
@api.doc(params={'kosha': 'Dictionary code on Cologne', 'term': 'term to search', 'intran': 'input transliteration'})
class CKT(Resource):
    """Return result for given query in given dictionary."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self, kosha, term, intran):
        kosha = kosha.lower()
        r = requests.get('https://sanskrit-lexicon.uni-koeln.de/scans/csl-apidev/api0/getsuggest.php?dict=' + kosha + '&term=' + term + '&input=' + intran)
        result = r.json()
        return result


@api.route('/' + apiversion + '/cologne/suggests/<string:term>/<string:kosha>')
@api.doc(params={'kosha': 'Dictionary code on Cologne', 'term': 'term to search'})
class STK(Resource):
    """Return pdf for given query in given dictionary."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self, kosha, term):
        kosha = kosha.lower()
        r = requests.get('https://sanskrit-lexicon.uni-koeln.de/scans/csl-apidev/api0/getsuggest.php?dict=' + kosha + '&term=' + term)
        result = r.json()
        return result


@api.route('/' + apiversion + '/cologne/pdfs/hws/<string:term>/<string:kosha>')
@api.doc(params={'kosha': 'Dictionary code on Cologne', 'term': 'term to search'})
class PKT(Resource):
    """Return pdf for given query in given dictionary."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self, kosha, term):
        kosha = kosha.lower()
        r = requests.get('https://sanskrit-lexicon.uni-koeln.de/scans/csl-apidev/api0/servepdf.php?dict=' + kosha + '&key=' + term)
        result = r.json()
        return result


@api.route('/' + apiversion + '/cologne/pdfs/pages/<string:page>/<string:kosha>')
@api.doc(params={'kosha': 'Dictionary code on Cologne', 'page': 'page number'})
class PKP(Resource):
    """Return pdf for given page in given dictionary."""

    get_parser = reqparse.RequestParser()

    @api.expect(get_parser, validate=True)
    def get(self, kosha, page):
        kosha = kosha.lower()
        r = requests.get('https://sanskrit-lexicon.uni-koeln.de/scans/csl-apidev/api0/servepdf.php?dict=' + kosha + '&page=' + page)
        result = r.json()
        return result


if __name__ == "__main__":
    # app.run(debug=True)
    app.run()
