from datetime import datetime
from helper import userrole, translit, remove_accents, cfg, serbian_sort_key



# viewmodel
class Browsed_entry:
    def __init__(self, headword: str, id: int, homograph=None):
        self.id = id
        if homograph:
            self.headline = headword + " " + str(homograph)
        else:
            self.headline = headword


# viewmodel
class User_statuses:
    def __init__(self, statuses: list):
        self.users = {"total": {"editing":[], "edited": [], "reded": [], "redacted" :[], "forred": [], "noted": []}}
        edited_by = {}
        self.skip = []
        for x in statuses:
            if x.status == "edited":
                edited_by[x.eid] = x.user
            if x.user not in self.users:
                self.users[x.user] = {"editing":[], "edited": [], "reded": [],"redacted" :[], "forred": [], "noted": []}
            if x.etype != "одредница":
                self.skip.append(x.eid)
            
        for x in statuses:
            if x.head:
                if x.head[-1]=="✱":
                    self.users[x.user]["noted"].append((x.head, x.eid))
                    self.users["total"]["noted"].append((x.head, x.eid))
            if x.status!="editing" or x.active:
                self.users[x.user][x.status].append((x.head, x.eid))
                self.users["total"][x.status].append((x.head, x.eid))
                if x.status == "redacted":
                    self.users[edited_by[x.eid]]["reded"].append((x.head, x.eid))
                    self.users["total"]["reded"].append((x.head, x.eid))

        for x in self.users:
            self.users[x]["forred"] =  [item for item in self.users[x]["edited"] if item not in self.users[x]["reded"] and item[1] not in self.skip]
            self.users[x]["editing"] =  [item for item in self.users[x]["editing"] if item not in self.users[x]["edited"]]
        self.users["total"]["editing"] =  [item for item in self.users["total"]["editing"] if item not in self.users["total"]["edited"]]
        self.users["total"]["forred"] =  [item for item in self.users["total"]["edited"] if item not in self.users["total"]["reded"] and item[1] not in self.skip]

        for x in self.users:
            for y in self.users[x]:
                self.users[x][y] = sorted(self.users[x][y], key=lambda o:serbian_sort_key(o[0]))


class Entry:
    def __init__(self, id: int, headwords_acc: list, headwords: list, pos: str, homograph: int, etype: str, rang: int, freq: int, headwords_acc_ijk: list):
        self.id = id
        self.headwords = [remove_accents(x) for x in headwords_acc]
        self.head = headwords_acc[0]
        self.headwords_acc = []
        self.headwords_acc_ijk = []
        if len(headwords_acc)>1:
            self.headwords_acc = headwords_acc[1:]
    
        if not headwords_acc_ijk:
            headwords_acc_ijk = []
        if len(headwords_acc_ijk)>0:
            self.head_ijk = headwords_acc_ijk[0]
            if len(headwords_acc_ijk)>1:
                self.headwords_acc_ijk = headwords_acc_ijk[1:]
            else:
                self.headwords_acc_ijk = []
        else:
            self.head_ijk = ""

        self.pos = pos
        if homograph:
            self.homograph = homograph
        else:
            self.homograph = ""

        self.type = etype
        self.rang = rang
        self.freq = freq
        CQL = '%5Blemma%3D%22' + '%7C'.join([translit(x) for x in self.headwords]) + '%22%5D'
        CQL2 = '%5Blemma%3D%5C%22' + '%7C'.join([translit(x) for x in self.headwords]) + '%5C%22%5D'
        self.noske21 = 'https://noske.jerteh.rs/#concordance?corpname=SrpKor2021&tab=advanced&queryselector=cql&attrs=word&viewmode=sen&attr_allpos=all&refs_up=0&shorten_refs=1&glue=1&gdexcnt=20&show_gdex_scores=0&itemsPerPage=20&structs=s,g&refs=doc&default_attr=lemma&cql=' + CQL +'&showresults=1&showTBL=0&tbl_template=&gdexconf=&f_tab=basic&f_showrelfrq=1&f_showperc=0&f_showreldens=0&f_showreltt=0&c_customrange=0&operations=%5B%7B%22name%22%3A%22cql%22%2C%22arg%22%3A%22' + CQL2 +'%22%2C%22query%22%3A%7B%22queryselector%22%3A%22cqlrow%22%2C%22cql%22%3A%22' + CQL2 +'%22%2C%22default_attr%22%3A%22lemma%22%7D%2C%22id%22%3A5460%7D%5D'
        self.noske13 = 'https://noske.jerteh.rs/#concordance?corpname=SrpKor2013&tab=advanced&queryselector=cql&attrs=word&viewmode=sen&attr_allpos=all&refs_up=0&shorten_refs=1&glue=1&gdexcnt=20&show_gdex_scores=0&itemsPerPage=20&structs=s,g&refs=doc&default_attr=lemma&cql=' + CQL +'&showresults=1&showTBL=0&tbl_template=&gdexconf=&f_tab=basic&f_showrelfrq=1&f_showperc=0&f_showreldens=0&f_showreltt=0&c_customrange=0&operations=%5B%7B%22name%22%3A%22cql%22%2C%22arg%22%3A%22' + CQL2 +'%22%2C%22query%22%3A%7B%22queryselector%22%3A%22cqlrow%22%2C%22cql%22%3A%22' + CQL2 +'%22%2C%22default_attr%22%3A%22lemma%22%7D%2C%22id%22%3A5460%7D%5D'
        self.zero = None
        self.senses = []
        self.pronunciations = []
        self.statuses = []
        self.expressions = []
        self.notes = []
        self.editable = False
        self.myentry = False
        self.redactable = False   


    def connect(self, senses: list, pronunciations: list, statuses: list, expressions: list, notes: list):
        self.zero = senses[0]
        if len(senses)>1:
            self.senses = senses[1:]
        self.pronunciations = pronunciations
        self.statuses = statuses
        self.expressions = expressions
        self.notes = notes
        user, role = userrole()
        if not statuses and role in ["editor", "redactor"]:
            self.editable = True
        else:
            if user in [x.user for x in statuses if x.active and x.status=="editing"]:
                self.myentry = True

            if  len([x.user for x in statuses if x.active and x.status=="edited"])>0 and role=="redactor":
                self.redactable = True
                self.myentry = True

            
class Status:
    def __init__(self, id: int,  user: str, status: str, time: datetime, eid: int, active: int):
        self.id = id
        self.eid = eid
        self.status = status
        self.user = user
        self.time = time
        self.active = bool(active)


class Status2:
    def __init__(self, id: int,  user: str, status: str, time: datetime, eid: int, active: int, head: str, homo: int, pos: str, note: str, etype: str):
        self.id = id
        self.eid = eid
        self.status = status
        self.user = user
        self.time = time
        self.head = head
        self.etype = etype

        if homo:
            self.head += "[" + str(homo) + "]"
        if pos:
            self.head += " " + pos
        if note=="приватна":
            self.head += " ✱"
        self.active = bool(active)


class Pronunciation:
    def __init__(self, id: int, sound: str, eid: int, ordinal: int, labels: list, transkriptions: list, headword: str, user: str):
        self.id = id
        self.eid = eid
        self.headword = headword
        self.sound = sound
        self.user = user
        self.labels = labels
        self.transcriptions = transkriptions


class Relation:
    def __init__(self, id: int, reltype: str, ord: int, description: str, lexicon_id: int ):
        self.id = id
        self.type = reltype
        self.ordinal = ord
        self.description = description
        self.lexicon_id = lexicon_id


class Member:
        def __init__(self, id: int, rid: int, member_sid: int, role: str, ord: int, ord2: int):
            self.id = id
            self.rid = rid
            self.member_sid = member_sid
            self.role = role
            self.ordinal = ord
            self.ordinal2 = ord2

class Sense:
    def __init__(self, id: int, eid: int, ordinal: int, label: str, domains: list, qualifiers: list, collocations: list, indicator: str, grammar: str, grammar_ijk: str):
        self.id = id
        self.eid = eid
        self.ord = ordinal
        if label is None:
            self.label=""
        else:
            self.label = label.strip()
        self.domains = domains
        if self.domains is None:
            self.domains = []
        self.qualifiers = qualifiers
        if self.qualifiers is None:
            self.qualifiers = []
        self.grammartext = grammar
        if self.grammartext is None:
            self.grammartext = ""
        self.grammartext_ijk = grammar_ijk
        if self.grammartext_ijk is None:
            self.grammartext_ijk = ""
        self.collocations = collocations
        if self.collocations is None:
            self.collocations = []
        self.indicator = indicator
        if self.indicator is None:
            self.indicator=""
        self.grammars = []
        self.definitions = []
        self.examples = []
        self.connected = []

    def connect(self, grammars: list, definitions: list, examples: list, connected: list, my: bool):
        self.grammars = grammars
        self.definitions = definitions
        self.examples = examples
        self.mysense = my
        self.connected = connected



# sta je lokus???
class Example:
    def __init__(self, id: int, sid: int, ordianl: int, label: str, text: str, type: str, start_idx: int, end_idx: int, locus: str):
        self.id = id
        self.sid = sid
        self.label = label
        self.text = text.strip()
        self.start_idx = start_idx
        self.end_idx = end_idx
        if type:
            self.type = type
        else:
            self.type = cfg["examples"][0]
        self.locus = locus


class Definition:
    def __init__(self, id: int, sid: int, type: str, ordinal: int, text: str):
        self.id = id
        self.sid = sid
        self.ordinal = ordinal
        self.text = text.strip()
        self.type = type


class Grammar:
    def __init__(self, id: int, sid: int, tag: str, text: str, ordinal: int):
        self.id = id
        self.sid = sid
        self.ordinal = ordinal
        self.text = text.strip()
        self.tag = tag


class Expression:
    def __init__(self, entry_id: int, sense_id: int, head: str, rid: int, role: str):
        self.eid = entry_id
        self.sid = sense_id
        self.head = head
        self.rid = rid
        self.role = role


class Note:
    def __init__(self, note_id: int, entry_id: int, type: str, note: str, author: str):
        self.id = note_id
        self.eid = entry_id
        self.type = type
        self.note = note.strip()
        self.author = author


def json_default(value):
    try:
        x = value.__dict__
    except:
        x = ""
    return x
