# news key word catch
import os
import random
import time
import tushare as ts
import math
import pandas
import threading
from MYSORT import *
from programdiary import *
import Stock_config_kit as Skit
import ForgeModel

COLLECTORSHOWNUM=5
fgt={'a':0.01,'a_2':0.01,'lam':0.01}
DIARYNAME='DIARY_Ver.0.1_ty2_0.01_0.01'

def readsinatime(timestr):
    if timestr:
        try:
            Year=int(time.strftime('%Y',time.gmtime()) )
            [F,L]=timestr.split(' ')
            [mon,day]=F.split('-')
            [hour,minus]=L.split(':')
            mon=int(mon)
            day=int(day)
            hour=int(hour)
            minus=int(minus)
            # in time.mktime the #6, #7's value do not matter (#0--#8)
        except:
            print('the timestr is not enough for unpacking process :%s'%timestr)
            [Year,mon,day,hour,minus]=[2016,0,0,0,0]
    else:
        [Year,mon,day,hour,minus]=[2016,0,0,0,0]
    return time.mktime( (Year,mon,day,hour,minus,0,0,0,0) )

class loopobj(threading.Thread):
    loopflag=0 #1 means stop
    def __init__(self):
        threading.Thread.__init__(self)

    def setlooppara(self,span,funchandle,*funcpara):
        self.span=span
        self.funch=funchandle
        self.funcpara=funcpara

    def stoploop(self):
        self.loopflag=1

    def timeloop(self):
        print(self.name+ ': loop start')
        while self.loopflag==0:
            time.sleep(self.span)
            if self.funcpara[0]==None:
                self.funch()
            else:
                #self.funch(self.funcpara)
                #print('stock')
                parastr=''
                for i in range(len( self.funcpara)):
                    parastr+='self.funcpara[%d]'% (i)
                eval('self.funch(%s)'%parastr)


        print(self.name+ '  timeloop end')

    def run(self):
        self.timeloop()

class Keyword:

    wordset=None
    Counter=0
    distribution=None
    weight=None
    show_dis_flag=False

    def 
__init__(self,wordset,weight):
        if(isinstance(word
set,list)):
            self.wordset=wordset
            self.distribution=[0 for n in range(len( wordset) )]   ######################## good!
            self.weight=weight
            self._sortkeyword()

    def modify_keyword(self,mode,M_KW):
        if not isinstance(mode,1):

            if(mode==1):
                # delte keyword from KW
                # delte the relavant distri from KW
                for KW in M_KW:
                    I=self.index(KW)
                    self.wordset.remove(KW)
                    self.distribution.remove(self.distribution[I])
                    self.weight.remove(self.weight[I])
                    # or del self.distribution[I]

            elif(mode==2):
                for KW in M_KW:
                    self.wordset.append(KW)
                    self.distribution.append(0)
                    self.weight.append(1)

                self._sortkeyword(self)
                # creat%
                # creat$
            else:
                print('Unknown Mode Number. mode=1 for subtracting keywords,mode=2 for adding keywords')

    def modify_distri(self,prey):
        ind=0
        for ele in prey:
            self.distribution[ind]+=ele
            ind+=1

    def show_distri(self):
        # print like 'word': times 'word2': times
        i=0
        output=''
        while i<len(self.distribution):
            output+='%s: %s  '%(self.wordset[i],self.distribution[i])
            i+=1
        print(output)

    def hunt(self,preystr):
        i=0
        dis=[0 for n in range(len( self.wordset))]
        c_flag=False
        for key in self.wordset:
            findcounter=False
            findhead=-1
            for j in range(len(self.wordset)):
                findhead=preystr.find( key , findhead+1 )
                if findhead == -1:
                    break
                findcounter+=int(bool(1+findhead))
                c_flag=True
            dis[i]+=findcounter
            #self.distribution[i]+=findcounter
            i+=1

        self.modify_distri(dis)
        if c_flag==True and self.show_dis_flag==True:
            self.show_distri()

    def _sortkeyword(self):
        try:
            List_one=self.wordset
            Capital_L_one=[]
            for element in List_one:
                try:
                    Capital_L_one.append( ord( element[0] ) )
                except:
                    print(self.name,'   :',element )
            [self.wordset,self.distribution,self.weight]=mysort(Capital_L_one,self.wordset,self.distribution,self.weight)
        except:
            print(self.name,'  ',self.wordset)

class stock_info(Keyword,loopobj,ForgeModel.Forge):
    name=''
    code=''
    browsetime=''
    Name_W=1
    Code_W=1
    Area_W=1
    Ind_W=2
    Con_W=2

    def __init__(self,name='',code='',area=[],industry=[],concept=[],a=fgt['a'],a_2=fgt['a_2'],lam=fgt['lam']):
        #some time later would add a return to creat more cal
        self.name=name
        self.code=code
        self.area=area
        self.industry=industry
        self.concept=concept
        #self.business=business
        ForgeModel.Forge.__init__(self,a,a_2,lam)

        Keyword.__init__(self,[code]+[name]+area+industry+concept,self.ini_weight() )
        loopobj.__init__(self)

    def ini_weight(self):
        W=[self.Code_W,self.Name_W]

        if self.area:
            W.append(self.Area_W)

        if isinstance( self.industry,list) and self.industry!=[]:
            for i in self.industry:
                W.append(self.Ind_W)


        if isinstance( self.concept,list) and self.concept!=[]:
            for i in self.concept:
                W.append(self.Con_W)
        return W

    def Trum(self,Newsobj):
        if Newsobj.latesttime!=self.browsetime:
            brt=readsinatime(self.browsetime)
            newst=readsinatime(Newsobj.latesttime)
            if brt==(0,0,0,0,0,0,0,0,0):
                deltat=0
            elif newst==(0,0,0,0,0,0,0,0,0):
                deltat=0
            else:
                deltat=newst-brt

            self.stimulate_forge_type2(self.distribution,deltat)
            self.browsetime=Newsobj.latesttime
            self.hunt(Newsobj.latestnew)
        else:
            pass

class News(loopobj):
    name=None
    newslength=1
    show_c=True
    Newsmemory= pandas.DataFrame()
    latesttime=''
    latestnew=''

    def __init__(self,name):
        self.name=name
        loopobj.__init__(self)

    def modify_newspara(self,nl,show_c):
        self.newslength=nl
        self.show_c=show_c

    def Newsget(self):
        #PDnews=ts.get_latest_news(top=self.newslength,show_content=self.show_c)
        PDnews=ts.get_latest_news(top=self.newslength,show_content=False)

        try:
            if PDnews.ix[0,'time']!=self.latesttime:
                Newsmemory=pandas.concat([self.Newsmemory,PDnews],axis=0) #按行合并
                #self.latesttime=PDnews.ix[0,'time']
                if self.show_c:
                    try:
                        Content=None
                        C_C=0
                        while not Content and C_C<5:
                            Content=ts.latest_content(PDnews.ix[0,'url'])
                            C_C+=1
                    except:
                        print('latest_content api fail to load url:%s'%PDnews.ix[0,'url'])
                        Content=''

                    #self.latestnew=PDnews.ix[0,'classify']+PDnews.ix[0,'title']+Content
                    self.latestnew=PDnews.ix[0,'title']+Content
                else:
                    #self.latestnew=PDnews.ix[0,'classify']+PDnews.ix[0,'title']  #maybe content later
                    self.latestnew=PDnews.ix[0,'title']
                print(PDnews[['classify','title','time']])

                if PDnews.ix[0,'time']:
                    print('old latesttime %s'%self.latestt