#!/usr/bin/env python

from __future__ import print_function
from __future__ import absolute_import
import string
from .jats import JATSParser
from .author_init import AuthorInitial
from pyingest.config.config import *


class NoSchemaException(Exception):
    pass


class WrongSchemaException(Exception):
    pass


class UnparseableException(Exception):
    pass


class OUPJATSParser(JATSParser):

    def oup_journals(self, pid):
        try:
            bibstem = OUP_PUBLISHER_IDS[pid]
        except KeyError:
            return 'XSTEM'
        else:
            return bibstem

    def get_tmp_page(self, bs):
        try:
            f = OUP_TMP_DIRS[bs.lower()]
        except Exception as err:
            pass
        else:
            f = f + "early.dat.nocheck"
            try:
                if sys.version_info > (3,):
                    open_mode = 'rb'
                else:
                    open_mode = 'rU'
                with open(f, open_mode) as fp:
                    p = fp.readline()
                return p.split()[0]
            except Exception as err:
                pass

    def update_tmp_file(self, bs, bib, doi):
        try:
            f = OUP_TMP_DIRS[bs.lower()]
        except Exception as err:
            pass
        else:
            f = f + "early.dat.nocheck"
            l = bib + "\t" + doi + "\n"
            try:
                with open(f, 'a') as fp:
                    fp.write(l)
                # now replace first line
                c = bib[14:18]
                c = c.replace('.', '')
                c = c + "\n"
                with open(f, 'r') as fp:
                    lines = fp.readlines()
                    # if you're replacing the first line, this is fine
                    lines[0] = c
                    # if you want to insert something before the first line,
                    # use this:
                    # lines.insert(0, c)
                with open(f, 'w') as fp:
                    # writelines doesn't need a return value, and doing this
                    # will destroy lines after it's done.
                    # lines = fp.writelines(lines)
                    fp.writelines(lines)
            except Exception as err:
                pass

    def dbfrombs(self, bs):
        db = []
        try:
            bibs = OUP_PUBLISHER_IDS[bs]
        except KeyError:
            return 'XSTEM'
        else:
            if bibs == 'ptep':
                database = "PHY"
            elif bibs == 'gji':
                database = "PHY"
            else:
                database = "AST"
        return database

    def getnexttmp(self, bs):
        tmpid = []
        try:
            bibs = OUP_PUBLISHER_IDS[bs]
        except KeyError:
            return 'XSTEM'
        else:
            database = "PHY"
        return tmpid

    def parse(self, input_data, **kwargs):