#!/usr/bin/python3

# ## {R2D2919B742E} ##
# ###########################################################################
# What if magic existed?
# What if a place existed where your every thought and dream come to life.
# There is only one catch: it has to be written down.
# Such a place exists, it is called programming.
#    - Scott Taylor Reph, RightThumb.com
# ###########################################################################
# ## {C3P0D40fAe8B} ##


##################################################
import os, sys, time
##################################################
import _rightThumb._construct as __
appDBA=__.clearFocus(__name__,__file__);__.appReg=appDBA;
def focus(parentApp='',childApp='',reg=True):
    global appDBA;f=__.appName(appDBA,parentApp,childApp);
    if reg:__.appReg=f;
    return f
import _rightThumb._base3 as _
fieldSet=_.l.vars(focus(),__name__,__file__,appDBA)
_.load()
##################################################
_v = __.imp('_rightThumb._vars')
_str = __.imp('_rightThumb._string')
##################################################


def sw():
    pass
    #b)--> examples
    # _.switches.register( 'Input', '-i' )
    #e)--> examples
    # _.switches.register( 'Files', '-f,-fi,-file,-files','file.txt', isData='glob,name,data,clean', description='Files', isRequired=False )

# __.setting('require-list',['Files,Plus','File,Has']) # todo
# __.setting('require-list',['Pipe','Files'])
__.setting('receipt-log')
__.setting('receipt-file')
__.setting('myFileLocations-skip-validation',False)
__.setting('require-pipe',False)
__.setting('require-pipe||file',False)
__.setting('pre-error',False)
__.setting('switch-raw',[])



_.appInfo[focus()] = {
    # 'app': '8facG-jo0Cxk',
    'file': 'vps-joplin-live-share.py',
    'liveAppName': __.thisApp( __file__ ),
    'description': 'Changes the world',
        # _.ail(1,'subject')+
        # _.aib('one')+
    'categories': [
                        'DEFAULT',
                ],
    'usage': [
                        # 'epy another',
                        # 'e nmap',
                        # '',
    ],
    'relatedapps': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'prerequisite': [
                        # 'p another -file file.txt',
                        # '',
    ],
    'examples': [
                        _.hp('p thisApp -file file.txt'),
                        _.linePrint(label='simple',p=0),
                        '',
    ],
    'columns': [
                       # { 'name': 'name', 'abbreviation': 'n' },
                       # { 'name': '{1}', 'abbreviation': '{0}', 'sort': '{2}' },
    ],
    'aliases': [
                       # 'this',
                       # 'app',
    ],
    'notes': [
                       # {},
    ],
}

_.appData[focus()] = {
        'start': __.startTime,
        'uuid': '',
        'audit': [],
        'pipe': False,
        'data': {
                    'field': {'sent': [], 'received': [] }, # { 'label': '', 'context': [],  }
                    'table': {'sent': [], 'received': [] },
        },
    }


def triggers():
    _.switches.trigger( 'Files', _.myFileLocations, vs=True )
    _.switches.trigger( 'Ago', _.timeAgo )
    _.switches.trigger( 'Folder', _.myFolderLocations )
    _.switches.trigger( 'URL', _.urlTrigger )
    _.switches.trigger( 'Duration', _.timeFuture )

_.l.conf('clean-pipe',True)
_.l.sw.register( triggers, sw )

########################################################################################
#b)--> examples
#d)--> code hints to quickly get started
    #n)--> inline examples
        # any(ele in 'scott5' for ele in list('0123456789'))
        # if _.switches.isActive('Test'): test(); return None;
        # result=[]; result=[ _.pr(line) for i, line, bi in _.numerate( _.isData(r=0) )]
        # bk=[];[  bk.append(rec['backup']) for rec in backupLog if path == rec['file']]; bk=bk[-1];
        # a=(1 if True else 0) <--# 
        #!)--> m=[[row[i] for row in matrix] for i in range(4)]

    #n)--> python globals
        # for k in globals(): print(k, eval(k) )

    #n)--> webpage from url
        # for subject in _.caseUnspecific( line, needle ): line = line.replace( subject, _.colorThis( subject, 'green', p=0 ) )

    #n)--> webpage from url
        # requests=__.imp('requests.post')
        #!)--> data=str(requests.post(url,data={}).content,'iso-8859-1')

    #n)--> import and backup example
        # _bk = _.regImp( __.appReg, 'fileBackup' ); _bk.switch( 'Silent' ); _bk.switch( 'isRunOnce' ); _bk.switch( 'Flag', 'APP' ); _bk.switch( 'DoNotSchedule' )
        # _bk.switch( 'Input', path ); bkfi = _bk.action();
    
    #n)--> inline
        # for rel in [ subject for subject in _.isData(r=0) if _.showLine(subject) ]: print(rel)

    #n)--> banner
        # banner=_.Banner(app); goss=banner.goss;
#e)--> examples
########################################################################################
#n)--> start

# /home/efm/public_html/assets/js/markdown/live.htm
# page-title
# doc-title
# markdown-here

def phone(number):
    number=str(number)
    number=number.lower()
    number=number.replace(',','x')
    number=number.replace(';','x')
    number=number.replace(' ','')
    number=number.replace('+','')
    number=number.replace('*','')
    number=number.replace('-','')
    number=number.replace('(','')
    number=number.replace(')','')
    number=number.replace('\r','')
    number=number.split('\n')[0]
    number=number.split('x')[0]
    n=re.sub('[^0-9]','', number)

    # for d in number:
    #     if d in '0123456789': n+=d
    if n.startswith('1'): n=n[1:]
    if len(n) < 10: return ''
    # if len(n) > 10: print(n,number)

    return format(int(n[:-1]), ",").replace(",", "-") + n[-1]


# _.pv(_.v.config)

def extract(data,path):
    def isEnd(line,path):
        if line.startswith('id:'):
            if line.split('id:')[1].strip()+'.md' == path.split(os.sep)[-1]: return True
        return False

    inside=False
    config=[]
    lines=[]
    for line in data.split('\n'):
        if inside and line == '~~~':
            inside=False
        elif line == '~~~yml':
            inside=True
            config=[]
        elif inside:
            if not config and not line.replace(' ','').lower() in _.v.config['registration']: inside=False
            if inside: config.append(line)
        else:
            if isEnd(line,path): break
            lines.append(line)
    _.v.fig=_.fromYML('\n'.join(config))
    _.v.fig['id']=path.split(os.sep)[-1].replace('.md','')
    return '\n'.join(lines)

def sfo2(fu):
    fu.replace('/',os.sep)
    fx=_.v.config['share']+os.sep+fu+os.sep
    while os.sep+os.sep in fx: fx=fx.replace(os.sep+os.sep,os.sep)
    return fx
def sfo(fu,fme='d'):
    fu=fu.replace(' ','')
    fo=_.v.config['share']+os.sep+fme+os.sep+_.v.fig['id'].replace('.md','')+os.sep
    fx = fo+fu+os.sep
    fx=fx.replace(os.sep+os.sep,os.sep)
    # _.pr(fx)
    return fx

def mkdir(fos,fme='d'):
    for foi in fos.split(','):
        fx=sfo(foi,fme)
        _v.mkdir(fx)

def share(path):
    ts=str(time.time()).split('.')[0]
    fi=_.getText(path,raw=True)
    fi=fi.replace('\r','')
    fi=fi.replace('~~~yaml','~~~yml')
    cl=extract(fi,path)
    fo=_.v.config['share']+os.sep+_.v.fig['id']+os.sep
    mkdir( ' notifications, users, sessions, checkboxes, approval, access, fig, dex, md ' )
    cll=cl.split('\n')
    label=cll[0]
    cll=cll[1:]
    md='\n'.join(cll)
    md=md.strip()

    figt=_.toYML(_.v.fig)

    
    shf = sha(figt)
    _dxf = sfo( 'dex' )+'figs.yml'
    dxf = _.getYML(_dxf)
    nw=[]
    if not shf in dxf:
        nw.append('fig')
        dxf[shf]=int(ts)
        _.saveYML( dxf, _dxf )
        _.saveYML(figt,sfo( 'fig' )+ts+'.yml')
        _.saveText(ts,sfo( 'fig' )+'live')

    shd = sha(md)
    _dxm = sfo( 'dex' )+'md.yml'
    dxm = _.getYML(_dxm)
    if not shd in dxm:
        nw.append('md')
        dxm[shd]=int(ts)
        if not os.path.isfile(sfo( 'md' )+'live'): _.saveText(fi, sfo( 'md' )+_.v.fig['id']+'.md' )
        _.saveYML( dxm, _dxm )
        _.saveText(label+'\n'+md,sfo( 'md' )+ts+'.md')
        _.saveText(ts,sfo( 'md' )+'live')

    if nw: [ (_.pr('\t',x)) for x in nw ]



    i=sfo2('i')
    _v.mkdir(i)
    # print('i:',i)
    shared = _.getYML(  sfo2('i')+'shared.yml'  )
    changed=False
    path=None
    if 'path'  in _.v.fig: path='path'
    if 'paths' in _.v.fig: path='paths'
    
    if path:
        for usr in _.v.fig[path]:
             if not usr in shared:
                changed=True
                if not usr in shared:
                    changed=True
                    shared[usr]={}
                if not _.v.fig[path][usr] in shared[usr]:
                    changed=True
                    shared[usr][_.v.fig[path][usr]]=_.v.fig['id']
    if changed: _.saveYML( shared, i+'shared.yml' )

    u=sfo2('i/u')
    _v.mkdir(u)
    for usr in shared:
        changed=False
        uy=u+usr+'.yml'
        ui = _.getYML(uy)
        for uf in shared[usr]:
            if not uf in ui:
                changed=True
                ui[uf]=shared[usr][uf]
        if changed: _.saveYML(ui,uy)

    us=sfo('users')
    # auth={}

    # _.pv(_.v.fig)

    for usr in _.v.fig['efm-share']:
        phn=phone(_.v.fig['efm-share'][usr])
        usd=us+phn+os.sep
        m5=md5( 'r2d2'+phn+'c3p0' )
        if not os.path.isdir(usd):
            _v.mkdir(usd)

        if not os.path.isdir(sfo2('u/p/'+phn)):
            _v.mkdir( sfo2('u/p/'+phn) )
            _.saveText( usr, sfo2('u/p/'+phn)+'name' )

        if not os.path.isdir(sfo2('u/n/'+usr)):
            _v.mkdir( sfo2('u/n/'+usr) )
            _.saveText( phn, sfo2('u/n/'+usr)+'phone' )

        if not os.path.isdir(sfo2('u/5/'+m5)):
            _v.mkdir( sfo2('u/5/'+m5) )
            _.saveText( phn, sfo2('u/5/'+m5)+'phone' )

        
            
    # print('shf',shf)
    # print('shd',shd)

    # print(md)
    # print(label)
    # _.pv(_.v.fig)
    # print(figt)
    # print('shf:',shf)


    # print(22,'here')

    


def scan(path):
    file = open( path, 'r' ).read(200)
    file=file.replace('~~~yaml','~~~yml').strip()
    file=file.replace('\r','')
    file=file.replace(' ','')
    while '~~~yml\n\n' in file: file=file.replace('~~~yml\n\n','~~~yml\n')
    good=False
    if '~~~yml' in file: good = any(('~~~yml\n' + reg in file) for reg in _.v.config['registration'])
    if good: good = any(state + '\n~~~' in file for state in _.v.config['state'])


    if good:
        print(  path.split(os.sep)[-1]  )
        share(path)

def action():
    fo=_.v.config['joplin']
    files=_.fo(fo)
    # print(files)
    for fi in files:
        if fi.endswith('.md'):
            # print(fi)
            scan(fi)

def sha(txt):
    import hashlib
    return hashlib.sha1(txt.encode()).hexdigest()

def md5(txt):
    import hashlib
    return hashlib.md5(txt.encode()).hexdigest()



_.v.config = {}
_.v.config['share']  = '/home/efm/public_html/s/'
_.v.config['joplin'] = '/home/efm/public_html/joplin01_a8e1'
_.v.config['html']   = '/home/efm/public_html/assets/js/markdown/live.htm'
_.v.config['registration'] = ['efm-share:','efm-groups:','efm-users:']
_.v.config['state'] = ['state:1']


import re
# print( sha('txt') )


##################################################
#b)--> examples
# banner=_.Banner(dependencies)
# goss=banner.goss
# goss('-\t this app will sherlock tf out of any python app or python module')
#e)--> examples
##################################################

########################################################################################
if __name__ == '__main__':
    #b)--> examples

    # banner.pr()
    # if len(_.switches.all())==0: banner.gossip()
    
    #e)--> examples
    action()
    _.isExit(__file__)
